C#测试数据库连接是否成功
1个回答
展开全部
/// 测试连接数据库是否成功
/// </summary
/// <returns</returns
public static bool ConnectionTest(){//获取数据库连接字符串
ConnectionString = ConnectionInfo.ConnectionString();
//创建连接对象
mySqlConnection = new SqlConnection(ConnectionString);
//ConnectionTimeout 在.net 1.x 可以设置 在.net 2.0后是只读属性,则需要在连接字符串设置
//如:server=.;uid=sa;pwd=;database=PMIS;Integrated Security=SSPI; Connection Timeout=30
//mySqlConnection.ConnectionTimeout = 1;//设置连接超时的时间try{//Open DataBase
//打开数据库
mySqlConnection.Open();
IsCanConnectioned = true;}catch{//Can not Open DataBase
//打开不成功 则连接不成功
IsCanConnectioned = false;}finally{//Close DataBase
//关闭数据库连接
mySqlConnection.Close();}//mySqlConnection is a SqlConnection object
if (mySqlConnection.State == ConnectionState.Closed || mySqlConnection.State == ConnectionState.Broken){//Connection is not available
return IsCanConnectioned;}else{//Connection is available
return IsCanConnectioned;}}}其中数据库字符串调用了类ConnectionInfo的方法ConnectionString
public class ConnectionInfo{public ConnectionInfo() { }
/// <summary
/// 从配置文件中读取数据库联接字符串
/// </summary
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询