¿Cómo comprobar si la cadena de conexión es válida?
Estoy escribiendo una aplicación en la que un usuario proporciona una cadena de conexión manualmente y me pregunto si hay alguna manera de validar la cadena de conexión, quiero decir verificar si es correcta y si la base de datos existe.
4 answers
¿Podrías intentar conectarte? Para una validación rápida (sin conexión), tal vez use DbConnectionStringBuilder
para analizarlo...
DbConnectionStringBuilder csb = new DbConnectionStringBuilder();
csb.ConnectionString = "rubb ish"; // throws
Pero para comprobar si la base de datos existe, tendrá que intentar conectarse. Más simple si conoce al proveedor, por supuesto:
using(SqlConnection conn = new SqlConnection(cs)) {
conn.Open(); // throws if invalid
}
Si solo conoce al proveedor como una cadena (en tiempo de ejecución), use DbProviderFactories
:
string provider = "System.Data.SqlClient"; // for example
DbProviderFactory factory = DbProviderFactories.GetFactory(provider);
using(DbConnection conn = factory.CreateConnection()) {
conn.ConnectionString = cs;
conn.Open();
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-12 09:16:27
Prueba esto.
try
{
using(var connection = new OleDbConnection(connectionString)) {
connection.Open();
return true;
}
}
catch {
return false;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-28 09:11:10
Si el objetivo es la validez y no la existencia, lo siguiente hará el truco:
try
{
var conn = new SqlConnection(TxtConnection.Text);
}
catch (Exception)
{
return false;
}
return true;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-21 15:09:52
Para sqlite use esto: Supongamos que tiene una cadena de conexión en el cuadro de texto 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
Creo que puedes fácilmente convertirlo a código c #
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-15 08:50:43