Development Tip

연결 문자열이 유효한지 확인하는 방법은 무엇입니까?

yourdevel 2020. 10. 23. 19:11
반응형

연결 문자열이 유효한지 확인하는 방법은 무엇입니까?


사용자가 연결 문자열을 수동으로 제공하는 응용 프로그램을 작성 중이며 연결 문자열을 확인할 수있는 방법이 있는지 궁금합니다. 올바른지, 데이터베이스가 있는지 확인해야합니다.


연결을 시도 할 수 있습니까? 빠른 (오프라인) 유효성 검사를 위해 아마도 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의 경우 다음을 사용하십시오. 텍스트 상자 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 # 코드로 쉽게 변환 할 수 있다고 생각합니다.

참고URL : https://stackoverflow.com/questions/434864/how-to-check-if-connection-string-is-valid

반응형