提取sql连接字符串的属性 [英] Extract properties of sql connection string

查看:25
本文介绍了提取sql连接字符串的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 connectionString(一个字符串变量)中提取服务器和数据库名称.当我们从 DEV 转移到 STAGE 再到 PROD 时,服务器和数据库的名称会发生​​变化.

I want to extract from a connectionString (a string variable) the server and database names. The name of the server and database change as we move from DEV to STAGE and then PROD.

这是一个例子:

Here's an example:

Data Source=SERVER_XYZ;Initial Catalog=DATABASE_XYZ;User ID=us;Password=pass

Data Source=SERVER_XYZPQR;Initial Catalog=DATABASE_XYZPQR;User ID=us;Password=pass

注意名称的变化(以及整个字符串的长度).

Notice the name changes (as well as lengths of the whole string).

如何在不知道数据源和初始目录的长度的情况下捕获它?这样在表单加载时,它就会得到 Server &显示给用户的数据库名称(以便他/她可以看到他/她连接到哪个服务器和数据库?

How do I capture the data source and initial catalog without knowing the length it's going to be? So that on form load, it'll get the Server & Database name to display to the user (so he/she can see which server and database he/she is connected to?

推荐答案

您可以使用连接字符串构建器类,该类一旦构建就具有数据源和初始目录属性

You can use the connection string builder class which once constructed has datasource and initial catalog properties

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx

string connStr = "Data Source=SERVERx;Initial Catalog=DBx;User ID=u;Password=p"; 

var csb = new SqlConnectionStringBuilder(connStr);

string dataSource = csb.DataSource;
string initialCatalog = csb.InitialCatalog;

让 .net 框架为您完成工作;) 不要搞乱子字符串或正则表达式

Let the .net framework do the work for you ;) no messing about with substrings or regexs

这篇关于提取sql连接字符串的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆