The Mighty Blog

Aug13

Written by:Will Strohl
8/13/2007 

Have you ever worked with an application that had many different connection strings and databases? It is sometimes necessary to grab some information from those connection strings. I have run into such a situation recently. Here is how to grab the database name from the connection string.

Have you ever worked with an application that had many different connection strings and databases?  It is sometimes necessary to grab some information from those connection strings.  I have run into such a situation recently.  Here is how to grab the database name from the connection string.

First of all, I am making use of Regular Expression in order to perform this task.  In doing so, I am right now assuming that the only parameters in a connection string that specify a database name are "Initial Catalog" and "Database".  This is true of SQL Server, but for other datasources, you will need to ammend the regular expression to reflect your own datasource connection string parameters.

Here is the snippet that will return a database name from your connection string:

Public Shared Function GetDatabaseName(ByVal ConnectionString As String) As String
     Dim strValue As String = String.Empty
     If Not String.IsNullOrEmpty(ConnectionString) Then
          Try
               Dim re As New Regex("(Initial Catalog=|Database=){1}([\w-]+)[;]?")
               ' this should match:
               ' $0 = Initial Catalog=DATABASENAME;
               ' $1 = Initial Catalog=
               ' $2 = DATABASENAME
               ' ... OR ...
               ' $0 = Database=DATABASENAME;
               ' $1 = DataBase=
               ' $2 = DATABASENAME
               ' return just the DB name from the connection string
               strValue = re.Match(ConnectionString).Groups(2).Value
          Catch
               strValue = String.Empty
          End Try
     Else
          strValue = String.Empty
     End If
     Return strValue.Trim
End Function 

As you can see, we first set a local object to hold our return value.  It is automatically set to return an empty string.  Next, as long as the argument passed into the method is populated, we test the string against our regular expression. 

This regular expression will return three match groups, as long as there is a database parameter in the connection string.  The third group is the value we really want.  So, we return the trimmed value of that (just in case there are any additional leading or trailing spaces).

Tags:

Your name:
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 
Add to Technorati Favorites
Tweet about my blog
Will Strohl - The Mighty Blog - RSS Feed

Tag Cloud

© Copyright 2004-2010 by Will Strohl. All rights reserved.Website skinned by: Ralph Williams