C# 判断数据库连接是否打开
1个回答
展开全部
根据平常的思维你应该在之前打开,然后判断它的状态。
测试代码如下:
1 连接数据库try{
String commandText="select count(*) from users";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(local);Initial
Catalog=classmate;User Id=sa;Password=sa";
SqlCommand cmd = new SqlCommand(commandText,conn);
conn.Open();
string count = cmd.ExecuteScalar().ToString();
if (conn.State == ConnectionState.Open){
Response.Write(count);
Response.Write("数据库连接成功!");
Response.Write("<scriptalert('连接已打开')</script");}
conn.Close();
if (conn.State == ConnectionState.Closed){
Response.Write("连接已关闭");
Response.Write("<scriptalert('连接已关闭')</script");}}
Response.Write("数据库连接失败"+ex.Message);}}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询