Will "the Mighty" Strohl

HOW TO: Return the Database Name from a 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).



blog comments powered by Disqus