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


78

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

Answers:


150

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

@videador您的意思是“无效的语法”吗?还是“语法正确但信息错误?” -显然,如果它看起来不错,但服务器名称或密码错误,则必须尝试连接以进行检查。如果sqlite使用无效字符串“ Open()”,那么这听起来像SQLite中的错误
Marc Gravell

@MarcGravell我听说您不应将异常用于流控制。有什么方法可以做到而又不会引发异常?还是这是最好的方法?也许是上述规则的“例外” :)
bernie2436

1
@MarcGravell-我的评论基于文档所说的If the SqlConnection goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling Close.
Geoff

3
@MarcGravell-在评论之前,我应该更加努力地搜索:)我看到了Dispose()来电Close()
Geoff

16

试试这个。

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

我尝试了您的代码,它按预期运行,但是在连接超时到期后抛出。我试图在连接字符串中将连接超时设置为1秒,没有任何改变。这个问题有方法解决吗?
Alican Uzun

6

如果目标是有效性而不是存在,则可以使用以下方法:

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.