zoukankan      html  css  js  c++  java
  • C#测试数据库连接是否成功

    代码
    C#测试数据库连接是否成功


    新建ConnectionTestInfo类
    using System.Data.SqlClient;
    using System.Data;

    public class ConnectionTestInfo
    {
    private static SqlConnection mySqlConnection; //mySqlConnection is a SqlConnection object
    private static string ConnectionString = "";
    private static bool IsCanConnectioned = false;

    /// <summary>
    /// 测试连接数据库是否成功
    /// </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>
    /// <returns></returns>
    public static string ConnectionString()
    {
    return (ConfigurationSettings.AppSettings["ConnectionString"]);
    }

    }

  • 相关阅读:
    焦虑来回走
    去省政府客串
    中国地质大学(北京)招生信息有点坑
    张桂梅校长再获殊荣,实至名归!她的故事值得一看再看……
    行内容转为列内容
    公文写作心得
    钟南山院士亲口说的“如何保持健康长寿
    VMware虚拟机出现“内部错误”如何解决?
    CI框架深入篇(2)一些基础的我之不知道的标准格式
    SQL语句学习记录(三)
  • 原文地址:https://www.cnblogs.com/JoshuaDreaming/p/1887997.html
Copyright © 2011-2022 走看看