回顾一下ado.net,呵呵,今天做了一个小测试,公用一个连接,首先插入数据,然后显示,都没有错,执行3的时候出错了,原因是没有写红色的using语句,只知道SqlDataReader 以独占方式连接数据库,其他连接在它释放关闭前是不能使用的,那第一步用的连接,第二部照样可以用,why?
Test1
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("server=.;database=foods;integrated security=true"))
{
con.Open();
string sql = "Insert into visit values('10450','10450','a','d','2010-01-27 11:26:21','','','')";
SqlCommand comd = new SqlCommand();
comd.Connection = con;
comd.CommandText = sql;
int i = comd.ExecuteNonQuery(); //1
if (i > 0)
{
Response.Write("ok");
comd.CommandText = "Select * from visit";
using (SqlDataReader dr = comd.ExecuteReader()) //2
{
gvTest.DataSource = dr;
gvTest.DataBind();
}
}
else
{
Response.Write("no");
}
comd.CommandText = sql;
int a = comd.ExecuteNonQuery(); //3
if (a > 0)
{
Response.Write("yes");
}
}
}
{
using (SqlConnection con = new SqlConnection("server=.;database=foods;integrated security=true"))
{
con.Open();
string sql = "Insert into visit values('10450','10450','a','d','2010-01-27 11:26:21','','','')";
SqlCommand comd = new SqlCommand();
comd.Connection = con;
comd.CommandText = sql;
int i = comd.ExecuteNonQuery(); //1
if (i > 0)
{
Response.Write("ok");
comd.CommandText = "Select * from visit";
using (SqlDataReader dr = comd.ExecuteReader()) //2
{
gvTest.DataSource = dr;
gvTest.DataBind();
}
}
else
{
Response.Write("no");
}
comd.CommandText = sql;
int a = comd.ExecuteNonQuery(); //3
if (a > 0)
{
Response.Write("yes");
}
}
}