关于SqlConnection.Close()和Dispose()方法该何时调用

archu 2011-01-05 01:22:57
这是一个老生常谈的问题了,但是看到这里经常会有各种各样的回答。有的说用完之后两个方法最好都调用一下,有的说不调用的话就会导致连接池满,……

总之,似乎并没有统一的标准答案。让我们先看看MSDN吧:http://msdn.microsoft.com/en-us/library/ff647768.aspx

这上面提到的关闭数据库连接的两种标准做法:


public void DoSomeWork()
{
SqlConnection conn = new SqlConnection(connectionString);
…try
{
conn.Open();
// Do Work
}
catch (Exception e)
{
// Handle and log error
}
finally
{
if(null!=conn)
conn.Close();
}
}



using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
. . .
} // Dispose is automatically called on the conn variable here


显而易见,我们并不需要同时调用两个方法,只要调用Close()或者Dispose()中的任意一个就可以了,理由很简单,看看Dispose()的实现就知道了。

/// <summary>
/// Releases all resources used by the <see cref="T:System.ComponentModel.Component" />.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}

protected override void Dispose(bool disposing)
{
if (disposing)
{
this._userConnectionOptions = null;
this._poolGroup = null;
this.Close();
}
this.DisposeMe(disposing);
base.Dispose(disposing);
}


也就是说,调了Dispose()方法之后,它会自动调用Close()方法的。其实,对于Close()来说,并不是真正地把数据库连结给关闭了,只是放回到的连接池而已;这一点,很多人会误以为调用了Close()就是把连接关闭了。

那么,如果不调用Dispose()或者Close()又会怎样呢?
当你的程序并不需要频繁地操作数据库的时候,就算忘记调用Dispose或者Close也无伤大雅,因为SqlConnection类实现了Finalize方法,而Finalize方法里面又调用了Dispose。所以,最终Finalizer Queue在回收资源的时候也会调用到SqlConnection的Close()方法的。

其实,关于这一切MSDN上面都说得很清楚:
•Using either the Close method or the Dispose method is sufficient. You do not have to call one method after the other. There is no benefit to calling one method after the other.
•Dispose internally calls Close. In addition, Dispose clears the connection string.
•If you do not call Dispose or Close, and if you do not use the using statement, you are reliant upon the finalization of the inner object to free the physical connection.
•Use the using statement, instead of Dispose or Close, when you are working with a single type, and you are coding in Visual C#®. Dispose is automatically called for you when you use the using statement, even when an exception occurs.
•If you do not use the using statement, close connections inside a finally block. Code in the finally block always runs, regardless of whether an exception occurs.
•You do not have to set the SqlConnection reference to null or Nothing because there is no complex object graph. Setting object references to null or to Nothing is usually done to make a graph of objects unreachable.

...全文
1202 38 打赏 收藏 转发到动态 举报
写回复
用AI写文章
38 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
close和dispose可以同时使用吗,会有问题吗
anbin0814 2011-01-21
  • 打赏
  • 举报
回复
[Quote=引用 33 楼 archu 的回复:]
引用 31 楼 anbin0814 的回复:

推荐使用try、 catch conn.Close()
这样可以扑捉异常,
用using没有办法扑捉异常,而且用using 必须的实现IDisposible接口 运行完成后他会把连接释放,下次需要重新连接


这位同学,你千万不要误导人家啊。你的前半部分关于“不能捕捉异常”是正确的,至于后面的“把连接释放,下次需要重新连接”就是完全错误……
[/Quote]

我只弄过连接关闭,没用过连接释放
anbin0814 2011-01-20
  • 打赏
  • 举报
回复
推荐使用try、 catch conn.Close()
这样可以扑捉异常,
用using没有办法扑捉异常,而且用using 必须的实现IDisposible接口 运行完成后他会把连接释放,下次需要重新连接
Crossgate_J 2011-01-20
  • 打赏
  • 举报
回复
SqlConnection.Close();
apple130 2011-01-20
  • 打赏
  • 举报
回复
[Quote=引用 22 楼 jiangqixian 的回复:]
OK

引用 14 楼 subxli 的回复:
也就是说,调了Dispose()方法之后,它会自动调用Close()方法的。其实,对于Close()来说,并不是真正地把数据库连结给关闭了,只是放回到的连接池而已;这一点,很多人会误以为调用了Close()就是把连接关闭了。
[/Quote]

学习~
渔舟唱晚, 2011-01-20
  • 打赏
  • 举报
回复
有啊!
C5662601 2011-01-20
  • 打赏
  • 举报
回复
除了DataReader需要关闭 其它都不用考虑
roseorgun 2011-01-20
  • 打赏
  • 举报
回复
我也一般用USING的
archu 2011-01-20
  • 打赏
  • 举报
回复
[Quote=引用 31 楼 anbin0814 的回复:]

推荐使用try、 catch conn.Close()
这样可以扑捉异常,
用using没有办法扑捉异常,而且用using 必须的实现IDisposible接口 运行完成后他会把连接释放,下次需要重新连接
[/Quote]

这位同学,你千万不要误导人家啊。你的前半部分关于“不能捕捉异常”是正确的,至于后面的“把连接释放,下次需要重新连接”就是完全错误的了。

用了using之后,相当于以下的代码

SqlConnection conn = new SqlConnection(connString);
try
{
conn.Open();
}
finally
{
conn.Dispose();
}


最终会调用到Dispose()方法。对于SqlConnection来讲,调用Dispose或者Close的本质是差不多的,最终都是把连接返回到连接池里面。

请你仔细阅读并理解内部原理之后再发表高见,呵呵。
archu 2011-01-19
  • 打赏
  • 举报
回复
还有要分的吗?
笨熊熊 2011-01-07
  • 打赏
  • 举报
回复
現在要麽就用Using
要麽就close();dispose();
sshenry1151 2011-01-07
  • 打赏
  • 举报
回复
养成好习惯,使用完后CLOSE掉啊!
julian 2011-01-05
  • 打赏
  • 举报
回复
OK
[Quote=引用 14 楼 subxli 的回复:]
也就是说,调了Dispose()方法之后,它会自动调用Close()方法的。其实,对于Close()来说,并不是真正地把数据库连结给关闭了,只是放回到的连接池而已;这一点,很多人会误以为调用了Close()就是把连接关闭了。
[/Quote]
阿非 2011-01-05
  • 打赏
  • 举报
回复
你想说明什么?
newdigitime 2011-01-05
  • 打赏
  • 举报
回复
[Quote=引用 17 楼 wanzhengcheng 的回复:]
<script>alert('123');</script>

我要看看这句话会被弹窗不
[/Quote]
太无视CSDN技术员了.弹你JJ
wanzhengcheng 2011-01-05
  • 打赏
  • 举报
回复
<script>alert('123');</script>

我要看看这句话会被弹窗不
newdigitime 2011-01-05
  • 打赏
  • 举报
回复
我也一般用using
或者 conn.Close();

微软自己的代码就这样写了,大家还怕什么.
subxli 2011-01-05
  • 打赏
  • 举报
回复
也就是说,调了Dispose()方法之后,它会自动调用Close()方法的。其实,对于Close()来说,并不是真正地把数据库连结给关闭了,只是放回到的连接池而已;这一点,很多人会误以为调用了Close()就是把连接关闭了。
xuan.ye 2011-01-05
  • 打赏
  • 举报
回复
活到老,学到老

长知识了
萤火架构 2011-01-05
  • 打赏
  • 举报
回复
最好是明确的写上
加载更多回复(2)
一款特别好用的.net数据库链接通用类。 using System; using System.Collections; using System.Collections.Specialized; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Data.Common; using System.Collections.Generic; namespace CMS.DBUtility { /// /// 数据访问抽象基础类 /// Copyright (C) 2004-2008 By LiTianPing /// public abstract class DbHelperSQL { //数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库. public static string connectionString = PubConstant.ConnectionString; public DbHelperSQL() { } #region 公用方法 /// /// 判断是否存在某表的某个字段 /// /// 表名称 /// 列名称 /// 是否存在 public static bool ColumnExists(string tableName, string columnName) { string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'"; object res = GetSingle(sql); if (res == null) { return false; } return Convert.ToInt32(res) > 0; } public static int GetMaxID(string FieldName, string TableName) { string strsql = "select max(" + FieldName + ")+1 from " + TableName; object obj = GetSingle(strsql); if (obj == null) { return 1; } else { return int.Parse(obj.ToString()); } } public static bool Exists(string strSql) { object obj = GetSingle(strSql); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } /// /// 表是否存在 /// /// /// public static bool TabExists(string TableName) { string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1"; //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')"; object obj = GetSingle(strsql); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } public static bool Exists(string strSql, params SqlParameter[] cmdParms) { object obj = GetSingle(strSql, cmdParms); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } #endregion #region 执行简单SQL语句 /// /// 执行SQL语句,返回影响的记录数 /// /// SQL语句 /// 影响的记录数 public static int ExecuteSql(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } public static int ExecuteSqlByTime(string SQLString, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = Times; int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } /// /// 执行Sql和Oracle滴混合事务 /// /// SQL命令行列表 /// Oracle命令行列表 /// 执行结果 0-由于SQL造成事务失败 -1 由于Oracle造成事务失败 1-整体事务执行成功 public static int ExecuteSqlTran(List list, List oracleCmdSqlList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; SqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { foreach (CommandInfo myDE in list) { string cmdText = myDE.CommandText; SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; PrepareCommand(cmd, conn, tx, cmdText, cmdParms); if (myDE.EffentNextType == EffentNextType.SolicitationEvent) { if (myDE.CommandText.ToLower().IndexOf("count(") == -1) { tx.Rollback(); throw new Exception("违背要求"+myDE.CommandText+"必须符合select count(..的格式"); //return 0; } object obj = cmd.ExecuteScalar(); bool isHave = false; if (obj == null && obj == DBNull.Value) { isHave = false; } isHave = Convert.ToInt32(obj) > 0; if (isHave) { //引发事件 myDE.OnSolicitationEvent(); } } if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine) { if (myDE.CommandText.ToLower().IndexOf("count(") == -1) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "必须符合select count(..的格式"); //return 0; } object obj = cmd.ExecuteScalar(); bool isHave = false; if (obj == null && obj == DBNull.Value) { isHave = false; } isHave = Convert.ToInt32(obj) > 0; if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须大于0"); //return 0; } if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须等于0"); //return 0; } continue; } int val = cmd.ExecuteNonQuery(); if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0) { tx.Rollback(); throw new Exception("SQL:违背要求" + myDE.CommandText + "必须有影响行"); //return 0; } cmd.Parameters.Clear(); } string oraConnectionString = PubConstant.GetConnectionString("ConnectionStringPPC"); bool res = OracleHelper.ExecuteSqlTran(oraConnectionString, oracleCmdSqlList); if (!res) { tx.Rollback(); throw new Exception("Oracle执行失败"); // return -1; } tx.Commit(); return 1; } catch (System.Data.SqlClient.SqlException e) { tx.Rollback(); throw e; } catch (Exception e) { tx.Rollback(); throw e; } } } /// /// 执行多条SQL语句,实现数据库事务。 /// /// 多条SQL语句 public static int ExecuteSqlTran(List SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; SqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { int count = 0; for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n]; if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; count += cmd.ExecuteNonQuery(); } } tx.Commit(); return count; } catch { tx.Rollback(); return 0; } } } /// /// 执行带一个存储过程参数的的SQL语句。 /// /// SQL语句 /// 参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加 /// 影响的记录数 public static int ExecuteSql(string SQLString, string content) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// /// 执行带一个存储过程参数的的SQL语句。 /// /// SQL语句 /// 参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加 /// 影响的记录数 public static object ExecuteSqlGet(string SQLString, string content) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(SQLString, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText); myParameter.Value = content; cmd.Parameters.Add(myParameter); try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例) /// /// SQL语句 /// 图像字节,数据库的字段类型为image的情况 /// 影响的记录数 public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(strSQL, connection); System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image); myParameter.Value = fs; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } finally { cmd.Dispose(); connection.Close(); } } } /// /// 执行一条计算查询结果语句,返回查询结果(object)。 /// /// 计算查询结果语句 /// 查询结果(object) public static object GetSingle(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } public static object GetSingle(string SQLString, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); cmd.CommandTimeout = Times; object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } } } } /// /// 执行查询语句,返回SqlDataReader ( 注意:调用方法后,一定要对SqlDataReader进行Close ) /// /// 查询语句 /// SqlDataReader public static SqlDataReader ExecuteReader(string strSQL) { SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(strSQL, connection); try { connection.Open(); SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return myReader; } catch (System.Data.SqlClient.SqlException e) { throw e; } } /// /// 执行查询语句,返回DataSet /// /// 查询语句 /// DataSet public static DataSet Query(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } public static DataSet Query(string SQLString, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.SelectCommand.CommandTimeout = Times; command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } #endregion #region 执行带参数的SQL语句 /// /// 执行SQL语句,返回影响的记录数 /// /// SQL语句 /// 影响的记录数 public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } catch (System.Data.SqlClient.SqlException e) { throw e; } } } } /// /// 执行多条SQL语句,实现数据库事务。 /// /// SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[]) public static void ExecuteSqlTran(Hashtable SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); SqlParameter[] cmdParms = (SqlParameter[])myDE.Value; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// /// 执行多条SQL语句,实现数据库事务。 /// /// SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[]) public static int ExecuteSqlTran(System.Collections.Generic.List cmdList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { int count = 0; //循环 foreach (CommandInfo myDE in cmdList) { string cmdText = myDE.CommandText; SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine) { if (myDE.CommandText.ToLower().IndexOf("count(") == -1) { trans.Rollback(); return 0; } object obj = cmd.ExecuteScalar(); bool isHave = false; if (obj == null && obj == DBNull.Value) { isHave = false; } isHave = Convert.ToInt32(obj) > 0; if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave) { trans.Rollback(); return 0; } if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave) { trans.Rollback(); return 0; } continue; } int val = cmd.ExecuteNonQuery(); count += val; if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0) { trans.Rollback(); return 0; } cmd.Parameters.Clear(); } trans.Commit(); return count; } catch { trans.Rollback(); throw; } } } } /// /// 执行多条SQL语句,实现数据库事务。 /// /// SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[]) public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { int indentity = 0; //循环 foreach (CommandInfo myDE in SQLStringList) { string cmdText = myDE.CommandText; SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; foreach (SqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.InputOutput) { q.Value = indentity; } } PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); foreach (SqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.Output) { indentity = Convert.ToInt32(q.Value); } } cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// /// 执行多条SQL语句,实现数据库事务。 /// /// SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[]) public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { SqlCommand cmd = new SqlCommand(); try { int indentity = 0; //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); SqlParameter[] cmdParms = (SqlParameter[])myDE.Value; foreach (SqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.InputOutput) { q.Value = indentity; } } PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); foreach (SqlParameter q in cmdParms) { if (q.Direction == ParameterDirection.Output) { indentity = Convert.ToInt32(q.Value); } } cmd.Parameters.Clear(); } trans.Commit(); } catch { trans.Rollback(); throw; } } } } /// /// 执行一条计算查询结果语句,返回查询结果(object)。 /// /// 计算查询结果语句 /// 查询结果(object) public static object GetSingle(string SQLString, params SqlParameter[] cmdParms) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand()) { try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (System.Data.SqlClient.SqlException e) { throw e; } } } } /// /// 执行查询语句,返回SqlDataReader ( 注意:调用方法后,一定要对SqlDataReader进行Close ) /// /// 查询语句 /// SqlDataReader public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms) { SqlConnection connection = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand(); try { PrepareCommand(cmd, connection, null, SQLString, cmdParms); SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return myReader; } catch (System.Data.SqlClient.SqlException e) { throw e; } // finally // { // cmd.Dispose(); // connection.Close(); // } } /// /// 执行查询语句,返回DataSet /// /// 查询语句 /// DataSet public static DataSet Query(string SQLString, params SqlParameter[] cmdParms) { using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, SQLString, cmdParms); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds; } } } private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) cmd.Transaction = trans; cmd.CommandType = CommandType.Text;//cmdType; if (cmdParms != null) { foreach (SqlParameter parameter in cmdParms) { if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } cmd.Parameters.Add(parameter); } } } #endregion #region 存储过程操作 /// /// 执行存储过程,返回SqlDataReader ( 注意:调用方法后,一定要对SqlDataReader进行Close ) /// /// 存储过程名 /// 存储过程参数 /// SqlDataReader public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters) { SqlConnection connection = new SqlConnection(connectionString); SqlDataReader returnReader; connection.Open(); SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.CommandType = CommandType.StoredProcedure; returnReader = command.ExecuteReader(CommandBehavior.CloseConnection); return returnReader; } /// /// 执行存储过程 /// /// 存储过程名 /// 存储过程参数 /// DataSet结果中的表名 /// DataSet public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.Fill(dataSet, tableName); connection.Close(); return dataSet; } } public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); SqlDataAdapter sqlDA = new SqlDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); sqlDA.SelectCommand.CommandTimeout = Times; sqlDA.Fill(dataSet, tableName); connection.Close(); return dataSet; } } /// /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值) /// /// 数据库连接 /// 存储过程名 /// 存储过程参数 /// SqlCommand private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = new SqlCommand(storedProcName, connection); command.CommandType = CommandType.StoredProcedure; foreach (SqlParameter parameter in parameters) { if (parameter != null) { // 检查未分配值的输出参数,将其分配以DBNull.Value. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null)) { parameter.Value = DBNull.Value; } command.Parameters.Add(parameter); } } return command; } /// /// 执行存储过程,返回影响的行数 /// /// 存储过程名 /// 存储过程参数 /// 影响的行数 /// public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected) { using (SqlConnection connection = new SqlConnection(connectionString)) { int result; connection.Open(); SqlCommand command = BuildIntCommand(connection, storedProcName, parameters); rowsAffected = command.ExecuteNonQuery(); result = (int)command.Parameters["ReturnValue"].Value; //Connection.Close(); return result; } } /// /// 创建 SqlCommand 对象实例(用来返回一个整数值) /// /// 存储过程名 /// 存储过程参数 /// SqlCommand 对象实例 private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) { SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); command.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null)); return command; } #endregion } }
附登陆代码: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; namespace 图书馆管理信息系统 { /// /// Form1 的摘要说明。 /// public class login : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.TextBox userid; private System.Data.SqlClient.SqlConnection sqlConnection1; private System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1; private System.Data.SqlClient.SqlCommand sqlSelectCommand1; private System.Data.SqlClient.SqlCommand sqlInsertCommand1; private System.Data.SqlClient.SqlCommand sqlUpdateCommand1; private System.Data.SqlClient.SqlCommand sqlDeleteCommand1; private 图书馆管理信息系统.DataSet1 dataSet11; private System.Windows.Forms.TextBox textboxpass; /// /// 必需的设计器变量。 /// private System.ComponentModel.Container components = null; public login() { // // Windows 窗体设计器支持所必需的 // InitializeComponent(); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// /// 清理所有正在使用的资源。 /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows 窗体设计器生成的代码 /// /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(login)); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label();

62,051

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧