C# 判断数据库连接是否打开
(2010-01-02 14:08:03)
标签:
it
根据平常的思维你应该在之前打开,然后判断它的状态。
测试代码如下:
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("");
}
conn.Close();
if (conn.State == ConnectionState.Closed)
{
Response.Write("连接已关闭");
Response.Write("");
}
}
catch(Exception ex)
{
Response.Write("数据库连接失败"+ex.Message);
}
}
分享:
喜欢
0
赠金笔
加载中,请稍候......
评论加载中,请稍候...
发评论
登录名: 密码: 找回密码 注册记住登录状态
昵 称:
评论并转载此博文
发评论
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。