VB.net Checking if database exists before connecting to it
<p>I <a href="https://stackoverflow.com/questions/679000/how-to-check-if-a-database-exists-in-sql-server">found</a> the following query in order to find out if a database table was created already or not:</p>

<pre><code>if db_id('thedbName') is not null
   --code mine :)
   print 'db exists'
else
   print 'nope'
</code></pre>

<p>Now I am wanting to use that same query within my VB.net application. This is the code I currently have elsewhere that connects to the database (that I am wanting to see if its there before doing all this):</p>

<pre><code>Dim cn As SqlConnection = New SqlConnection("Data Source=DAVIDSDESKTOP;" &amp; _
                                            "Initial Catalog=thedbName;" &amp; _
                                            "Integrated Security=True;" &amp; _
                                            "Pooling=False")

    Dim sql As String = "if db_id('thedbName') is not null " &amp; vbCrLf &amp; _
                            "Print() 'exists' " &amp; vbCrLf &amp; _
                        "else " &amp; vbCrLf &amp; _
                            "Print() 'nope'"

    Dim cmd As SqlCommand = New SqlCommand(sql, cn)

    cmd.Connection.Open()
    Dim blah As String = cmd.ExecuteNonQuery()
    cmd.Connection.Close()
</code></pre>

<p>Of course the issue with this is that I have to know the database name first in order to connect to the database.</p>

<p>I then seem to be able to connect to the <em>master</em> database using this:</p>

<pre><code>Dim cn As SqlConnection = New SqlConnection("Data Source=DAVIDSDESKTOP;" &amp; _
                                            "Integrated Security=True;" &amp; _
                                            "Pooling=False")

    Dim sql As String = "if db_id('thedbName') is not null " &amp; vbCrLf &amp; _
                            "Print() 'exists' " &amp; vbCrLf &amp; _
                        "else " &amp; vbCrLf &amp; _
                            "Print() 'nope'"

    Dim cmd As SqlCommand = New SqlCommand(sql, cn)

    cmd.Connection.Open()
    Dim blah As String = cmd.ExecuteNonQuery()
    cmd.Connection.Close()
</code></pre>

<p>But that query seems to throw an error on <strong>Dim blah As String = cmd.ExecuteNonQuery()</strong> of:</p>

<blockquote>
  <p>Additional information: Incorrect syntax near ')'.</p>
</blockquote>

<p>So I'm not all sure what I am missing in order to correct the issue with the query?</p>

<p><strong>Need to know how to have the query come back and say 'exists' or 'nope'</strong></p>