質問
ユーザーが接続文字列を手動で提供するアプリケーションを作成していますが、接続文字列を検証できる方法があるかどうか疑問に思っています-それが正しいかどうか、データベースが存在するかどうかを確認します。
解決
接続を試みることができますか?すばやく(オフラインで)検証するには、おそらく 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#コードに簡単に変換できると思います
所属していません StackOverflow