如何检查连接字符串是否有效?

92

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


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

165
你可以尝试连接一下吗?为了快速(离线)验证,也许可以使用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();
    }

1
当使用System.data.sqlite时,这段代码片段不起作用。除非dbcon执行查询,否则用户无法知道连接字符串是否正确。 - dlopezgonzalez
@MarcGravell 我听说在流程控制中不应该使用异常。有没有不抛出和捕获异常的方法来实现这个功能?或者这是目前最好的方法吗?也许可以对上述规则做一个“例外” :) - bernie2436
你可能想要确保在 conn.Open() 后面也跟着 conn.Close() - Geoff
1
@MarcGravell - 我的评论基于文档中的内容,即“如果SqlConnection超出范围,则不会关闭。因此,您必须通过调用Close显式关闭连接。” - Geoff
3
我应该在评论之前更努力地搜索 :) 我看到Dispose()调用了Close() - Geoff
显示剩余4条评论

17

试一试。

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

我尝试了你的代码,它按预期工作,但是在连接超时后会抛出异常。我尝试在连接字符串中将连接超时设置为1秒,但没有任何改变。这个问题有解决方案吗? - Alican Uzun

8
如果目标是有效性而不是存在性,则以下内容可满足要求:
try
{
    var conn = new SqlConnection(TxtConnection.Text);
}
catch (Exception)
{
    return false;
}
return true;

0

对于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#代码


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接