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

怎样对数据库链接、数据库命令等使用using 语句
sql数据库,要用到储存过程
举些例子好吗!

------解决方案--------------------
using (SqlConnection con = new SqlConnection( "xxx "))
{
SqlCommand xx xxxxxxx...........
}

------解决方案--------------------
using (SqlConnection con = new SqlConnection( "xxx "))
{
....
}

1.{....}需要SqlConnetcion这个资源
2.{....}这段语句执行完毕以后立即dispose SqlConnetcion
偶的理解,高手指证.
------解决方案--------------------
要加上CLOSe
因为他是Disponse并没有关闭
------解决方案--------------------
using (SqlConnection conn = new SqlConnection(MyConnectionString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = MyStoredProcedureName;
//int rowsAffected = cmd.ExecuteNonQuery();
// ...

}
------解决方案--------------------
public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) {

SqlCommand cmd = new SqlCommand();

using (SqlConnection conn = new SqlConnection(connectionString)) {
PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
}

/// <summary>
/// Prepare a command for execution
/// </summary>
/// <param name= "cmd "> SqlCommand object </param>
/// <param name= "conn "> SqlConnection object </param>
/// <param name= "trans "> SqlTransaction object </param>
/// <param name= "cmdType "> Cmd type e.g. stored procedure or text </param>
/// <param name= "cmdText "> Command text, e.g. Select * from Products </param>
/// <param name= "cmdParms "> SqlParameters to use in the command </param>
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, 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 = cmdType;

if (cmdParms != null) {
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
}
}

petshop 4.0中的,我只看见了open,没有看见close.所以偶认为dispose的前提需要关闭连接

------解决方案--------------------
出了using块,会自动销毁掉
------解决方案--------------------
xinshijiuu() ( ) 信誉:100
先搞个数据库的命名空间不就可以USING啦.
======================================================

汗!


using (SqlConnection con = new SqlConnection( "xxx "))
{
....
}

1.{....}需要SqlConnetcion这个资源
2.{....}这段语句执行完毕以后立即dispose SqlConnetcion
偶的理解,高手指证.
---------------------------------