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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/434864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:15:20  来源:igfitidea点击:

How to check if connection string is valid?

c#connection-string

提问by agnieszka

I'm writing an application where a user provides a connection string manually and I'm wondering if there is any way that I could validate the connection string - I mean check if it's correct and if the database exists.

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

采纳答案by Marc Gravell

You could try to connect? For quick (offline) validation, perhaps use DbConnectionStringBuilderto parse it...

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

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

But to check whether the db exists, you'll need to try to connect. Simplest if you know the provider, of course:

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

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

If you only know the provider as a string (at runtime), then use DbProviderFactories:

如果您只知道提供程序作为字符串(在运行时),则使用DbProviderFactories

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

回答by Rashad Annara

Try this.

尝试这个。

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

回答by CBlafer

If the goal is validity and not existence, the following will do the trick:

如果目标是有效性而不是存在,则以下内容将起作用:

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

回答by GGSoft

For sqlite use this: Suppose you have connection string in textbox txtConnSqlite

对于 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

I think you can easilly convert it to c# code

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