title: Restore database in SQL LocalDB using VB.NET
body: <p>I have a project developed in VB.NET and SQL Server 2012 LocalDB (v11) and I am need backup/restore facility in my application. Backup part is complete but I am stuck at restore part. This is the query I want to be worked (and its working fine in SQL Editor)</p>
  
  <pre><code>ALTER DATABASE [&lt;.MDF File Path&gt;] 
  SET SINGLE_USER WITH ROLLBACK IMMEDIATE
  
  RESTORE DATABASE [&lt;.MDF File Path] FROM DISK='&lt;.bak File Path'
  </code></pre>
  
  <p>and here is the code in VB.NET I am trying to execute</p>
  
  <pre><code>Sub Restorequery(ByVal que As String)
      MainForm.Conn.Close()
      con = New SqlConnection("Data Source=(LocalDB)\v11.0;Database=Master;integrated security=True;")
      If Not con.State = ConnectionState.Open Then con.Open()
      cmd = New SqlCommand(que, con)
      cmd.ExecuteNonQuery()
  End Sub
  </code></pre>
  
  <p>And here are the approaches I tried so far </p>
  
  <ol>
  <li><p>Using the same query as above</p>
  
  <pre><code>Restorequery("ALTER DATABASE [&lt;.MDF File Path&gt;] SET SINGLE_USER WITH ROLLBACK IMMEDIATE")
  Restorequery("restore database [&lt;.MDF File Path&gt;] from disk='&lt;.bak File Path&gt;'")
  </code></pre>
  
  <p>and this results in an error </p>
  
  <blockquote>
    <p>Exclusive access could not be obtained because the database is in use. RESTORE DATABASE is terminating abnormally.</p>
  </blockquote></li>
  <li><p>After finding reason for above issue (which is nonsense even after using <code>master</code> database while opening connection and closing all the previously opened connections using <code>MainForm.Conn.Close()</code> ), I tried second approach as per some links and references from Stackoverflow. And here are the queries I tried:</p>
  
  <pre><code>Restorequery("use [master] ")
  Restorequery("alter database [&lt;.MDF File Name&gt;] set single_user with rollback immediate")
  Restorequery("restore database[&lt;.MDF File Name&gt;] from disk='&lt;.bak File Name&gt;'")
  Restorequery("alter database [&lt;.MDF File Name&gt;] set multi_user")
  Restorequery("use [&lt;.MDF File Name&gt;]")
  </code></pre>
  
  <p>and here is the error I got while executing second query :</p>
  
  <blockquote>
    <p>Additional information: User does not have permission to alter database &lt;.MDF File Name with Path>, the database does not exist, or the database is not in a state that allows access checks. ALTER DATABASE statement failed.</p>
  </blockquote></li>
  </ol>
  
  <p>Is there any other way to restore a SQL Server LocalDB using VB.NET ?</p>