你们一起做的都是错误的,你们应该创建连接,但不应该打开它,你们应该在需要的时候打开它,然后关闭它
我建议也删除此功能,只需使用
using
public static string CreateConnection()
{
string ConnectionString = ConfigurationManager.ConnectionStrings[_connectionString].ConnectionString;
_connection = new SqlConnection(ConnectionString);
//remove this line
//_connection.Open();
return "0";
}
您也不需要此功能
public static void CloseConnection()
{
_connection.Close();
_connection.Dispose();
}
按照建议使用会有帮助的
我建议最好的方法就是
使用
并按如下方式处理conenction
using(SqlConnection con = new SqlConnection() )
{
}
如果您担心它会创建太多的对象,那么for information与数据库的连接是池化的,这意味着您可以在连接字符串中单独指定连接池信息,这样您就不必担心在创建连接对象时建立连接。
<add name="sqlConnectionString" connectionString="Data
Source=mySQLServer;Initial Catalog=myDatabase;Integrated
Security=True;Connection Timeout=15;Connection Lifetime=0;Min Pool Size=0;Max
Pool Size=100;Pooling=true;" />
上面是处理池的连接字符串
示例代码,这是我在项目中的做法,如果您看到我每次使用
使用
public class DbHelper
{
#region Private methods
private static OracleConnection GetConnection()
{
string connectionString = DbConnectionString.ConnectionString;
return new OracleConnection(connectionString);
}
private static OracleCommand GetCommand(OracleConnection connection, string commandText, OracleParameter[] param, bool isProcedure)
{
OracleCommand dbCommand = new OracleCommand();
dbCommand.Connection = connection;
dbCommand.CommandText = commandText;
if (param != null)
dbCommand.Parameters.AddRange(param);
if (isProcedure)
dbCommand.CommandType = CommandType.StoredProcedure;
return dbCommand;
}
#endregion
#region public methods
public static DataTable GetDataTable(string commandText, OracleParameter[] odbcPrams, bool isProcedure = false)
{
DataTable dt = new DataTable();
using (OracleConnection ODBCConn = GetConnection())
{
using (OracleCommand dbCommand = GetCommand(ODBCConn, commandText, odbcPrams, isProcedure))
{
ODBCConn.Open();
OracleDataAdapter da = new OracleDataAdapter(dbCommand);
da.Fill(dt);
}
}
return dt;
}
#endregion
}