Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract properties of sql connection string [duplicate]

Tags:

substring

c#

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).

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?

like image 493
JJ. Avatar asked Aug 03 '12 21:08

JJ.


2 Answers

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;

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

like image 178
Chris Moutray Avatar answered Oct 08 '22 02:10

Chris Moutray


A C# Regex solution:

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

// Match the server:
Match serverMatch = Regex.Match(input, @"Source=([A-Za-z0-9_.]+)", RegexOptions.IgnoreCase);

// Match the database:
Match databaseMatch = Regex.Match(input, @"Catalog=([A-Za-z0-9_]+)", RegexOptions.IgnoreCase);

// Get the string
if (serverMatch.Success)
{
  String server = serverMatch.Groups[1].Value;
}

Keep in mind valid characters for URLs:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=
like image 31
Chris Dargis Avatar answered Oct 08 '22 01:10

Chris Dargis