كيفية التحقق مما إذا كانت سلسلة الاتصال صالحة؟

StackOverflow https://stackoverflow.com/questions/434864

  •  10-07-2019
  •  | 
  •  

سؤال

أنا أكتب تطبيقًا يوفر فيه المستخدم سلسلة اتصال يدويًا وأتساءل عما إذا كان هناك أي طريقة يمكنني التحقق من صحة سلسلة الاتصال - أقصد التحقق مما إذا كانت صحيحة وما إذا كانت قاعدة البيانات موجودة.

هل كانت مفيدة؟

المحلول

هل يمكن أن تحاول الاتصال؟ للتحقق السريع (غير متصل) ، ربما الاستخدام DbConnectionStringBuilder لتحليلها ...

    DbConnectionStringBuilder csb = new DbConnectionStringBuilder();
    csb.ConnectionString = "rubb ish"; // throws

ولكن للتحقق مما إذا كان DB موجود ، ستحتاج إلى محاولة الاتصال. أبسط إذا كنت تعرف المزود ، بالطبع:

    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 استخدم هذا: افترض أن لديك سلسلة اتصال في Textbox 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

أعتقد أنه يمكنك تحويل Easilly إلى رمز C#

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top