public static DataSet GetDataSet(string stringSql)
{
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(stringSql, conn);
adapter.Fill(ds);
}
return ds;
}
public static int ExecuteScalar(string stringSql)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(stringSql, conn))
{
try
{
conn.Open();
object obj = cmd.ExecuteScalar();
int i = Convert.ToInt32(obj);
return i;
}
catch (System.Data.SqlClient.SqlException ex)
{
conn.Close();
throw ex;
}
}
}
}
好吧执行查询的时候没有Open怎么也可以查询?
还有什么时候用 using (SqlCommand cmd = new SqlCommand(stringSql, conn))
{ }
{
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(stringSql, conn);
adapter.Fill(ds);
}
return ds;
}
public static int ExecuteScalar(string stringSql)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(stringSql, conn))
{
try
{
conn.Open();
object obj = cmd.ExecuteScalar();
int i = Convert.ToInt32(obj);
return i;
}
catch (System.Data.SqlClient.SqlException ex)
{
conn.Close();
throw ex;
}
}
}
}
好吧执行查询的时候没有Open怎么也可以查询?
还有什么时候用 using (SqlCommand cmd = new SqlCommand(stringSql, conn))
{ }
都可以用SqlCommand cmd = new SqlCommand(stringSql, conn)cmd.ExecuteNonQuery();
cmd.ExecuteReader();
2、using的写法是很优美的写法,用于自动释放对象。即出了{}大括号,cmd自动销毁,无需手动释放。
string connString = @"Data Source=. 省略若干字符;";
string sql = "select * from Manage_Table";
SqlConnection cn = new SqlConnection(connString);
SqlCommand cm = new SqlCommand(sql,cn);
SqlDataAdapter da = new SqlDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt); Response.Write(dt.Rows.Count);
Response.Write("<br>");
Response.Write(cn.State );
运行结果是44
Closed到数据库里取了数据,一共有44条,然后状态是 close。请问我的这段代码有啥问题没?(不考虑资源有没有及时释放)如果没啥问题的话,那么请问,是啥时候close的呢?
就需要 open close。 你在用 SqlCommand 不就是已经打开了么
using 里面会不会自动close?
C# code
?
1
2
3
4
5
6
7
8
9
10
11
string connString = @"Data Source=. 省略若干字符;";
string sql = "select * from Manage_Table";
SqlConnection cn = new SqlConnection(connString);
SqlCommand cm = new SqlCommand(sql,cn);
SqlDataAdapter da = new SqlDataAdapter(cm);
DataTable dt = new DataTable();
da.Fill(dt);
Response.Write(dt.Rows.Count);
Response.Write("<br>");
Response.Write(cn.State );
运行结果是44
Closed到数据库里取了数据,一共有44条,然后状态是 close。 请问我的这段代码有啥问题没?(不考虑资源有没有及时释放) 如果没啥问题的话,那么请问,是啥时候close的呢?
SqlDataAdapter对象会根据需要打开连接,但是不会更改连接的状态,
所以如果连接之前是关闭的,在SqlDataAdapter对象Fill完后还是关闭的,
如果是打开的,Fill完还是打开的
“如果连接之前是关闭的,在SqlDataAdapter对象Fill完后还是关闭的,”fill前是关闭的,fill中一定是打开了对吧,否则无法填充数据。然后fill之后呢?你说了,是关闭的,那么是谁关闭的呢?不是 SqlDataAdapter吗?所以我说 SqlDataAdapter 可以自动close,这个并没有错。我举的例子并没有事先手动open。