C#从SQLServer连接字符串获取SQLServer服务器信息

dreams1981 2011-02-25 10:25:43
在网上找到的一个方法

string strCnn="Data Source=.;Initial Catalog=DianJiCS;Persist Security Info=True;User ID=sa;Password=sa";

string[] strs;
strs = strCnn.Split(';');

string path = "";//数据库备份路径
string dataBaseName = "";//数据库名称
string hostName = "";//当前连接的SqlServer服务器名称
string userID = "";//SQLServer连接用户名
string password = "";//SQLServer连接密码

#region 获取

foreach (string str in strs)
{
if (str.Contains("Data Source") || str.Contains("Server"))//SQLServer服务器名称
{
hostName = str.Substring(str.IndexOf("=") + 1);
}
else
{
if (str.Contains("Initial Catalog") || str.Contains("Database"))
{
dataBaseName = str.Substring(str.IndexOf("=") + 1);
}
else
{
if (str.Contains("User ID") || str.Contains("UID"))
{
userID = str.Substring(str.IndexOf("=") + 1);
}
else
{
if (str.Contains("Password") || str.Contains("PWD"))
{
password = str.Substring(str.IndexOf("=") + 1);
}
}
}
}
}

#endregion

但觉得该方法有点问题,
1)str.Contains区分大小写的,(虽然可以用indexof解决)
2)strs = strCnn.Split(';'),str.IndexOf("=") 用";" "="分隔时.如果sa密码含有";"或"="时候就会出现问题


using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string DataSource = connection.DataSource;
string Database = connection.Database;
}

上面的方法也只能获取到 DataSource 跟 Database,用户密码无法获取

大家有更好的方法吗?
...全文
780 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Dobzhansky 2011-02-25
  • 打赏
  • 举报
回复

把那个字符串交给 SqlConnectionStringBuilder , 然后访问
SqlConnectionStringBuilder 对象的属性
不是更好吗

dreams1981 2011-02-25
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 dobzhansky 的回复:]

把那个字符串交给 SqlConnectionStringBuilder , 然后访问
SqlConnectionStringBuilder 对象的属性
不是更好吗
[/Quote]

这正是我想要的
dreams1981 2011-02-25
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 wuyq11 的回复:]
"(?is)^(?=.*Data Source=[^;]+)(?=.*Initial Catalog=[^;]+)(?=.*Persist Security Info=[^;]+)(?=.*User ID=[^;]+)(?=.*Password=[^;]+).*$"
[/Quote]

Data Source 名称可能是 server,User ID 可能是 uid,password 可能是 pwd
dreams1981 2011-02-25
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 wuyq11 的回复:]
"(?is)^(?=.*Data Source=[^;]+)(?=.*Initial Catalog=[^;]+)(?=.*Persist Security Info=[^;]+)(?=.*User ID=[^;]+)(?=.*Password=[^;]+).*$"
[/Quote]
这个怎么用?
wuyq11 2011-02-25
  • 打赏
  • 举报
回复
"(?is)^(?=.*Data Source=[^;]+)(?=.*Initial Catalog=[^;]+)(?=.*Persist Security Info=[^;]+)(?=.*User ID=[^;]+)(?=.*Password=[^;]+).*$"


dreams1981 2011-02-25
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 richet512 的回复:]
一般情况下,,有2中方式
第一,如楼主所述,数据库连接字符串直接写在配置文件中
第二,添加配置文件项,数据库服务器,database,用户名,密码都是配置项,
在使用的时候读出来,拼接起来,,

第二种方式,就不会有楼主的问题了
[/Quote]
我也知道添加配置文件项,这个是比较简单的解决方法,但通用性不那么好,
沅江汐水 2011-02-25
  • 打赏
  • 举报
回复
一般情况下,,有2中方式
第一,如楼主所述,数据库连接字符串直接写在配置文件中
第二,添加配置文件项,数据库服务器,database,用户名,密码都是配置项,
在使用的时候读出来,拼接起来,,

第二种方式,就不会有楼主的问题了

62,074

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧