4 ответов:
вы можете попробовать подключиться? Для быстрой (автономной) проверки, возможно, используйте
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#
Comments