从连接字符串中删除了数据库

时间:2022-04-08 11:14:54

I was given a method to get our database connection string to Sql Server:

我得到了一个方法来获取我们的数据库连接字符串到Sql Server:

SqlConnection GetConnectionString()

I call that and get what the connection string should be. If the database does not exist, I need the connection string without the database name in it. If I try to use the connection string with the database name in it, I get an error that it cannot connect to the database, which is it since it does not exist.

我调用它并得到连接字符串应该是什么。如果数据库不存在,我需要没有数据库名称的连接字符串。如果我尝试使用带有数据库名称的连接字符串,我会收到一个错误,它无法连接到数据库,因为它不存在。

I am calling like this:

我打电话是这样的:

using (var connection = new SqlConnection(GetConnectionString().ConnectionString))

Is there a way to recreate the connection string easily without the database name?

有没有办法在没有数据库名称的情况下轻松地重新创建连接字符串?

2 个解决方案

#1


9  

SqlConnectionStringBuilder aBuilder = 
   new SqlConnectionStringBuilder(yourConnectionStringWithDatabase);
aBuilder.InitialCatalog = "";

string yourConnectionStringWithoutDatabase = aBuilder.ConnectionString;

#2


0  

It's easy

var connectionString = "data source=someInstance;initial catalog =someDatabase;etc.";

var pattern = "initial catalog[=\\s\\w]+;";

var dbRemoved = Regex.Replace(connectionString, pattern, "");

Note that I haven't handled case sensitivity, but this should be a good start for your requirements.

请注意,我没有处理区分大小写,但这应该是您的要求的良好开端。

#1


9  

SqlConnectionStringBuilder aBuilder = 
   new SqlConnectionStringBuilder(yourConnectionStringWithDatabase);
aBuilder.InitialCatalog = "";

string yourConnectionStringWithoutDatabase = aBuilder.ConnectionString;

#2


0  

It's easy

var connectionString = "data source=someInstance;initial catalog =someDatabase;etc.";

var pattern = "initial catalog[=\\s\\w]+;";

var dbRemoved = Regex.Replace(connectionString, pattern, "");

Note that I haven't handled case sensitivity, but this should be a good start for your requirements.

请注意,我没有处理区分大小写,但这应该是您的要求的良好开端。