【问题标题】:How to check if connection string is valid?如何检查连接字符串是否有效?
【发布时间】:2010-09-30 21:30:14
【问题描述】:

我正在编写一个用户手动提供连接字符串的应用程序,我想知道是否有任何方法可以验证连接字符串 - 我的意思是检查它是否正确以及数据库是否存在。

【问题讨论】:

    标签: c# connection-string


    【解决方案1】:

    您可以尝试连接吗?对于快速(离线)验证,也许使用DbConnectionStringBuilder 来解析它...

        DbConnectionStringBuilder csb = new DbConnectionStringBuilder();
        csb.ConnectionString = "rubb ish"; // throws
    

    但要检查数据库是否存在,您需要尝试连接。如果您知道提供者,最简单的方法当然是:

        using(SqlConnection conn = new SqlConnection(cs)) {
            conn.Open(); // throws if invalid
        }
    

    如果你只知道提供者是一个字符串(在运行时),那么使用DbProviderFactories

        string provider = "System.Data.SqlClient"; // for example
        DbProviderFactory factory = DbProviderFactories.GetFactory(provider);
        using(DbConnection conn = factory.CreateConnection()) {
            conn.ConnectionString = cs;
            conn.Open();
        }
    

    【讨论】:

    • 当它使用 System.data.sqlite 时,这个 sn-p 不起作用。在 dbcon 不执行查询之前,用户不知道连接字符串是否正确。
    • @videador 你的意思是“无效的语法”吗?还是“语法有效但信息错误?” - 显然,如果它看起来很正常但服务器名称或密码错误,您必须尝试连接以检查。如果 sqlite 将使用无效字符串“Open()”,那么这听起来像是 SQLite 中的错误
    • @MarcGravell 我听说你不应该使用异常来控制流量。有没有办法在不抛出和捕获异常的情况下做到这一点?或者这是最好的方法吗?也许是上述规则的“例外”:)
    • @MarcGravell - 我的评论是基于docsIf the SqlConnection goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling Close.
    • @MarcGravell - 在评论之前我应该​​更加努力地搜索 :) 我看到 Dispose() 调用 Close()
    【解决方案2】:

    试试这个。

        try 
        {
            using(var connection = new OleDbConnection(connectionString)) {
            connection.Open();
            return true;
            }
        } 
        catch {
        return false;
        }
    

    【讨论】:

    • 我尝试了您的代码,它按预期工作,但是在连接超时到期后抛出。我试图在连接字符串中将连接超时设置为 1 秒,但没有任何改变。有解决办法吗?
    【解决方案3】:

    如果目标有效且不存在,则以下方法可以解决问题:

    try
    {
        var conn = new SqlConnection(TxtConnection.Text);
    }
    catch (Exception)
    {
        return false;
    }
    return true;
    

    【讨论】:

      【解决方案4】:

      对于 sqlite 使用这个:假设你在文本框 txtConnSqlite 中有连接字符串

           Using conn As New System.Data.SQLite.SQLiteConnection(txtConnSqlite.Text)
                  Dim FirstIndex As Int32 = txtConnSqlite.Text.IndexOf("Data Source=")
                  If FirstIndex = -1 Then MsgBox("ConnectionString is incorrect", MsgBoxStyle.Exclamation, "Sqlite") : Exit Sub
                  Dim SecondIndex As Int32 = txtConnSqlite.Text.IndexOf("Version=")
                  If SecondIndex = -1 Then MsgBox("ConnectionString is incorrect", MsgBoxStyle.Exclamation, "Sqlite") : Exit Sub
                  Dim FilePath As String = txtConnSqlite.Text.Substring(FirstIndex + 12, SecondIndex - FirstIndex - 13)
                  If Not IO.File.Exists(FilePath) Then MsgBox("Database file not found", MsgBoxStyle.Exclamation, "Sqlite") : Exit Sub
                  Try
                      conn.Open()
                      Dim cmd As New System.Data.SQLite.SQLiteCommand("SELECT * FROM sqlite_master WHERE type='table';", conn)
                      Dim reader As System.Data.SQLite.SQLiteDataReader
                      cmd.ExecuteReader()
                      MsgBox("Success", MsgBoxStyle.Information, "Sqlite")
                  Catch ex As Exception
                      MsgBox("Connection fail", MsgBoxStyle.Exclamation, "Sqlite")
                  End Try
                End Using
      

      我认为您可以轻松地将其转换为 c# 代码

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-21
        • 2011-06-17
        • 2018-02-02
        • 2018-11-15
        • 1970-01-01
        • 2019-05-05
        • 2019-10-04
        相关资源
        最近更新 更多