C#和数据库连接

来源:百度知道 编辑:UC知道 时间:2024/06/04 22:45:10
SqlConnection con;
SqlCommand com;
SqlDataReader dr;
private void DataReader(string sql)
{
string s = "server=.;database=buchongti;uid=sa";
con = new SqlConnection(s);
con.Open();
com = new SqlCommand(sql,con);
dr = com.ExecuteReader();
}

为什么con.open()不能放在其他方法里?
在其它的方法中调用DataReader()后
con.Open()
为什么会报错?

可以呀
但前提是你的con已经初始化,并且在其它方法中可见

你这里的数据库打开了没有关闭就不能够再在其他地方用咯!

con.open()意思是打开数据库,你调用DataReader()时肯定要打开啊,不打开怎么行

con.Open();
com = new SqlCommand(sql,con);
dr = com.ExecuteReader();
con.Close();