日期:2014-05-18  浏览次数:20479 次

access数据库时常连接出错
如果使用频率不高,没有问题,但如果连续的连接,就会出现不能连接的问题
代码如下:
public   static     OleDbConnection   con()
        {
                    string   strConnection   =   System.Configuration.ConfigurationSettings.AppSettings[ "connstr "]   +   System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationSettings.AppSettings[ "dbpath "]);
                OleDbConnection   connect   =   new   OleDbConnection(strConnection);  
                return   connect;
        }

  public   static   string   sel(string   i)
        {
                        string   strConnection   =   System.Configuration.ConfigurationSettings.AppSettings[ "connstr "]   +   System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationSettings.AppSettings[ "dbpath "]);
                        OleDbConnection   connect   =   new   OleDbConnection(strConnection);
                        connect.Open();
                        OleDbCommand   command   =   new   OleDbCommand(i,   connect);
                        OleDbDataReader   reader   =   command.ExecuteReader();
                        reader.Read();
                        return   (reader[0].ToString());
                        connect.Close();
        }

下面是web.config的代码
<appSettings>
<add   key= "connstr "   value= "Provider=Microsoft.Jet.OLEDB.4.0;Data   source= "/>
<add   key= "dbpath "   value= "~/database/cydb.mdb "/>
</appSettings>
出错的时候,抱错信息是在   connect.Open();高亮

------解决方案--------------------
显然,你的连接并没有关闭

return (reader[0].ToString()); // 已经 return 了,下一句 close 你说它还会执行嘛?
connect.Close();

》》

string result = reader[0].ToString();
connect.Close();
return result;
------解决方案--------------------
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
return (reader[0].ToString());
=======================================================
OleDbDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
reader.Read();
string result = reader[0].ToString();
reader.Close();
connect.Close();
return result;