Right way to get username and password from connection string? [duplicate]

半世苍凉 提交于 2019-12-31 19:20:30

问题


I have a connection string like this:

"SERVER=localhost;DATABASE=tree;UID=root;PASSWORD=branch;Min Pool Size = 0;Max Pool Size=200"

How do I get the various database parameters out of it? I can get database name and server like this:

serverName = conObject.DataSource;
dbName = conObject.Database;

I need the username and password as well similarly. No property is set on the MySqlConnection object.

At present I do it like this:

public static void GetDatabaseParameters(string connectionString, out string serverName, out string dbName, out string userName, out string password)
{
    Match m = Regex.Match(connectionString, "SERVER=(.*?);DATABASE=(.*?);UID=(.*?);PASSWORD=(.*?);.*");

    //serverName = m.Groups[1].Value;
    //dbName = m.Groups[2].Value;
    userName = m.Groups[3].Value;
    password = m.Groups[4].Value;
}

Is there an accepted practice here?


回答1:


You could use the SqlConnectionStringBuilder Class

string conString = "SERVER=localhost;DATABASE=tree;UID=root;PASSWORD=branch;Min Pool Size = 0;Max Pool Size=200";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(conString);
string user = builder.UserID;
string pass = builder.Password;


来源:https://stackoverflow.com/questions/9975122/right-way-to-get-username-and-password-from-connection-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!