Como verificar se a string de conexão é válida?
-
10-07-2019 - |
Pergunta
Estou escrevendo um aplicativo em que um usuário fornece uma string de conexão manualmente e estou me perguntando se existe alguma maneira de validar a string de conexão - quero dizer, verifique se está correta e se o banco de dados existe.
Solução
Você poderia tentar se conectar? Para validação rápida (offline), talvez use DbConnectionStringBuilder
Para analisar ...
DbConnectionStringBuilder csb = new DbConnectionStringBuilder();
csb.ConnectionString = "rubb ish"; // throws
Mas para verificar se o banco de dados existe, você precisará se conectar. Mais simples se você conhece o provedor, é claro:
using(SqlConnection conn = new SqlConnection(cs)) {
conn.Open(); // throws if invalid
}
Se você conhece apenas o provedor como uma string (em tempo de execução), use DbProviderFactories
:
string provider = "System.Data.SqlClient"; // for example
DbProviderFactory factory = DbProviderFactories.GetFactory(provider);
using(DbConnection conn = factory.CreateConnection()) {
conn.ConnectionString = cs;
conn.Open();
}
Outras dicas
Tente isso.
try
{
using(var connection = new OleDbConnection(connectionString)) {
connection.Open();
return true;
}
}
catch {
return false;
}
Se o objetivo for validade e não existência, o seguinte fará o truque:
try
{
var conn = new SqlConnection(TxtConnection.Text);
}
catch (Exception)
{
return false;
}
return true;
Para sqlite, use isto: suponha que você tenha a string de conexão na caixa de texto txtConnnsqlite
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
Eu acho que você pode convertê -lo para C#