title: C#: SQLite database always locked
body: <p>I've written a simple app (call it app1) that reads a SQLite database and display the contents in a gridview. I have a separate C# console app (app2) that needs to write to the same database. The problem is app2 fails with a "database is locked" error. I can see as soon as I start app1 a userdb-journal file is created. I assume the problem is that app1 opens the database but doesn't release it? This is the code I have for populating the Table I bind to the grid in app1.</p>
  
  <pre><code>    public DataTable GetAllPeople()
      {
          var connectionString = "Data Source=" + dbPath + ";Version=3";
  
          using (SQLiteDataAdapter sqlDataAdapter =
              new SQLiteDataAdapter("SELECT id,FirstName,LastName,Address FROM Users",
                                    connectionString))
          {
              using (DataTable dataTable = new DataTable())
              {
                  sqlDataAdapter.Fill(dataTable);
                  // code to add some new columns here
  
                  return dataTable;
              }
          }
      }
  </code></pre>
  
  <p>Here is the code that populates the gridview:</p>
  
  <pre><code>    private void Form1_Load(object sender, EventArgs e)
      {
          UserDatabase db = new UserDatabase();
          db.Initialize();
          dataGridView1.DataSource = db.GetAllPeople();
  
      }
  </code></pre>
  
  <p>How can I fix things so app2 can read and write to the database while app1 is running?</p>
  
  <p><strong>EDIT</strong>
  Looks like that journal file is only created by app2. I had only noticed the database locked error when app1 was running also, but perhaps app1 is a red herring. App2 is multi-threaded. Perhaps I should start a new question focusing on app2 and multithreaded access?</p>
  
  <p><strong>EDIT</strong>
  Thanks for all the comments. I've put a lock around all db accesses and wrapped everything up in usings. All seems to be working now.</p>