Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 716
nawfal Avatar asked Apr 02 '12 10:04

nawfal


1 Answers

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;
like image 182
ionden Avatar answered Oct 16 '22 15:10

ionden