86

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

4

4 回答 4

158

你可以尝试连接吗?对于快速(离线)验证,也许用于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();
    }
于 2009-01-12T09:10:14.000 回答
16

试试这个。

    try 
    {
        using(var connection = new OleDbConnection(connectionString)) {
        connection.Open();
        return true;
        }
    } 
    catch {
    return false;
    }
于 2014-03-28T09:11:10.203 回答
7

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

try
{
    var conn = new SqlConnection(TxtConnection.Text);
}
catch (Exception)
{
    return false;
}
return true;
于 2015-10-21T15:04:12.180 回答
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# 代码

于 2016-09-15T07:42:24.827 回答