문제

사용자가 연결 문자열을 수동으로 제공하는 응용 프로그램을 작성하고 연결 문자열을 검증 할 수있는 방법이 있는지 궁금합니다. 정확한지 확인하고 데이터베이스가 존재하는지 확인합니다.

도움이 되었습니까?

해결책

연결하려고 할 수 있습니까? Quick (오프라인) 검증을 위해서는 아마도 사용됩니다 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