数据查询和操纵时连接的打开状态

执行select语句时不需要Conn.Open()

using (SqlConnection Conn = new SqlConnection(connStr))
{
//Conn.Open();
string sql = "select * from school";
SqlCommand Comm = new SqlCommand(sql, Conn);
DataTable dt = new DataTable();//创建table
SqlDataAdapter da = new SqlDataAdapter(Comm);
da.Fill(dt);//直接将数据填充到datatable
n = Convert.ToInt32(dt.Rows[0][0]);
}

 

执行update、insert、delete是需要Conn.Open()

using (SqlConnection Conn = new SqlConnection(connStr))
{
Conn.Open();
string sql = "insert into school () values()";
SqlCommand Comm = new SqlCommand(sql, Conn);
Comm.ExecuteNonQuery();
}

posted @ 2015-08-01 10:37  net5x  阅读(150)  评论(0编辑  收藏  举报