title: SQLite: Why can't I DETACH a database when the main DB has an open prepared statement?
body: <p>Why does the following Code not work:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;sqlite3.h&gt;
  
  int main(void)
  {
      sqlite3 *pDb;
      sqlite3_stmt *stmt;
      char *errmsg;
  
      sqlite3_open(":memory:", &amp;pDb);
  
      sqlite3_exec(pDb, "CREATE TABLE Test(a INTEGER)", NULL, NULL, NULL);
      sqlite3_exec(pDb, "INSERT INTO Test(a) VALUES(1)", NULL, NULL, NULL);
  
      sqlite3_prepare_v2(pDb, "SELECT * FROM Test", -1, &amp;stmt, NULL);
      sqlite3_step(stmt);
  
      sqlite3_exec(pDb, "ATTACH 'Test.db' as Other;", NULL, NULL, NULL);
  
      sqlite3_exec(pDb, "DETACH Other;", NULL, NULL, &amp;errmsg);
      printf("error: %s\n", errmsg);
      return 0;
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>error: database Other is locked
  </code></pre>
  
  <p>If I do a <code>sqlite3_reset(stmt)</code> after the <code>sqlite3_step(stmt)</code>, it works.</p>
  
  <p>Why does an open statement on an unrelated database lock the "Other" database? I couldn't find an explanation in the docs.</p>