我要买二手车昆明:ASP.NET中SqlConnection的Open与Close方法 何时该用

来源:百度文库 编辑:高校问答 时间:2024/05/12 04:26:43
下面为一个Command对象实现存储过程访问的程序 在第9行处有nwConn.open();方法的调用. 请问何时该加此类方法 为什么有的程序加或不加都无所谓呢?

string strConnection="server=(local);database=NorthWind;user id=sa;password=loveshop;";
SqlConnection nwConn=new SqlConnection(strConnection);
SqlCommand empCmd=new SqlCommand("SearchEmp",nwConn);
empCmd.CommandType=CommandType.StoredProcedure;
SqlParameter empParm=empCmd.Parameters.Add("@EmpID",SqlDbType.NChar,6);
empParm.Value=6;
nwConn.Open();//此处如不加Open方法 程序就无法执行
SqlDataReader empReader=empCmd.ExecuteReader();

if(empReader.Read())
{
first_name.Text=empReader["FirstName"].ToString();
last_name.Text=empReader["LastName"].ToString();

}
empReader.Close();
nwConn.Close();
上面的程序只是调用的过程函数 来查询我所要的结果.

这个程序呢?为什么他不用调用open方法?
string strConnection="server=(local);database=NorthWind;user id=sa;password=loveshop;";
string queryStr="Select * from Employees"
SqlConnection nwConn=new SqlConnection(strConnection);
DataSet empSet=new DataSet();
SqlDataAdapter empAdapter= new SqlDataAdapter(queryStr,nwConn);
empAdapter.Fill(empSet);
empGrid.DataSource=empSet;
empGrid.DataBind();

不是加不加无所谓,而是如果要打开数据库对数据库进行操作的话,就必须要用Open方法,如果数据库已不再操作,可以使用Close方法将连接关闭。

你所见到的没有加,可能因为他在程序的其他公用部分已经加了。

为了避免不必要的错误发生,建议你还是加上,必须的。