How to check if connection string is valid?

前端 未结 4 1558
旧时难觅i
旧时难觅i 2020-11-28 22:48

I\'m writing an application where a user provides a connection string manually and I\'m wondering if there is any way that I could validate the connection string - I mean ch

4条回答
  •  囚心锁ツ
    2020-11-28 23:10

    You could try to connect? For quick (offline) validation, perhaps use DbConnectionStringBuilder to parse it...

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

    But to check whether the db exists, you'll need to try to connect. Simplest if you know the provider, of course:

        using(SqlConnection conn = new SqlConnection(cs)) {
            conn.Open(); // throws if invalid
        }
    

    If you only know the provider as a string (at runtime), then use DbProviderFactories:

        string provider = "System.Data.SqlClient"; // for example
        DbProviderFactory factory = DbProviderFactories.GetFactory(provider);
        using(DbConnection conn = factory.CreateConnection()) {
            conn.ConnectionString = cs;
            conn.Open();
        }
    

提交回复
热议问题