问题
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