如何检查连接string是否有效?

我正在写一个应用程序,用户提供一个连接string手动,我想知道是否有任何方法,我可以validation连接string – 我的意思是检查是否正确,如果数据库存在。

你可以尝试连接? 对于快速(离线)validation,也许使用DbConnectionStringBuilderparsing它…

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

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

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

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

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

尝试这个。

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

如果目标是有效的而不存在的话,那么下面的方法就是诀窍:

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

对于sqlite使用这个:假设你有连接string在文本框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 

我认为你可以easilly转换成C#代码