How to get Database Name from Connection String using SqlConnectionStringBuilder

后端 未结 7 1730
太阳男子
太阳男子 2020-12-02 21:52

I never want to split connection string using string manipulation and get server,database,uid and password.

I read the following link and read the accepted answer ,

相关标签:
7条回答
  • 2020-12-02 22:11

    You can use the provider-specific ConnectionStringBuilder class (within the appropriate namespace), or System.Data.Common.DbConnectionStringBuilder to abstract the connection string object if you need to. You'd need to know the provider-specific keywords used to designate the information you're looking for, but for a SQL Server example you could do either of these two things:

    System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);
    
    string server = builder.DataSource;
    string database = builder.InitialCatalog;
    

    or

    System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();
    
    builder.ConnectionString = connectionString;
    
    string server = builder["Data Source"] as string;
    string database = builder["Initial Catalog"] as string;
    
    0 讨论(0)
  • 2020-12-02 22:11

    Database name is a value of SqlConnectionStringBuilder.InitialCatalog property.

    0 讨论(0)
  • 2020-12-02 22:15

    A much simpler alternative is to get the information from the connection object itself. For example:

    IDbConnection connection = new SqlConnection(connectionString);
    var dbName = connection.Database;
    

    Similarly you can get the server name as well from the connection object.

    DbConnection connection = new SqlConnection(connectionString);
    var server = connection.DataSource;
    
    0 讨论(0)
  • 2020-12-02 22:21
    string connectString = "Data Source=(local);" + "Integrated Security=true";
    
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);
    
    Console.WriteLine("builder.InitialCatalog = " + builder.InitialCatalog);
    
    0 讨论(0)
  • 2020-12-02 22:35

    this gives you the Xact;

    System.Data.SqlClient.SqlConnectionStringBuilder connBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();
    
    connBuilder.ConnectionString = connectionString;
    
    string server = connBuilder.DataSource;           //-> this gives you the Server name.
    string database = connBuilder.InitialCatalog;     //-> this gives you the Db name.
    
    0 讨论(0)
  • 2020-12-02 22:36

    You can use InitialCatalog Property or builder["Database"] works as well. I tested it with different case and it still works.

    0 讨论(0)
提交回复
热议问题