[英]How to check if connection string is valid?
我正在編寫一個應用程序,其中用戶手動提供連接字符串,我想知道是否有任何方法可以驗證連接字符串 - 我的意思是檢查它是否正確以及數據庫是否存在。
你可以嘗試連接嗎? 為了快速(離線)驗證,也許使用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();
}
試試這個。
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 使用這個:假設你在文本框 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# 代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.