1

Whenever I call the test() method the code runs until it reaches the Messagebox.show() When i try to insert into the "vandute" table i get the error "DATABASE IS LOCKED"

private void test()
    {
        int z;
        SQLiteConnection dbcon = new SQLiteConnection("Data Source=stefanauto.psa;Version=3;");
        dbcon.Open();
        using (SQLiteCommand sql = new SQLiteCommand(dbcon))
        {
            sql.CommandText = "select ID from clienti where CNP='" + cnp.Text + "'";

            z = Convert.ToInt32(sql.ExecuteScalar());


            MessageBox.Show(z.ToString());//The error begins after this line
            sql.CommandText = "insert into vandute(ID_MASINA,ID_CLIENT)values(1,2)";//Id_MASINA,ID-CLIENT ARE integers
            sql.ExecuteNonQuery();
        }
    }

Can you please explain me what am I doing wrong?

SGS
  • 11
  • 2
  • 1
    I have found the solution [here](http://stackoverflow.com/questions/22612790/sqlite-database-is-locked-on-insertion)! – SGS Feb 18 '16 at 12:37

2 Answers2

1

Try to move the

dbcon.Open();

inside the using block. Something like

using (SQLiteConnection c = new SQLiteConnection("Data Source=stefanauto.psa;Version=3;"))
{
    c.Open();
    using (SQLiteCommand cmd = new SQLiteCommand(sql, c))
    {
        //your code
    }
}

or else try to dispose your connection explicitly

public void DisposeConnection()
{
    SQLiteConnection.Dispose();
    SQLiteCommand.Dispose();   
    GC.Collect();
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • I have only moved "SQLiteConnection dbcon = new SQLiteConnection("Data Source=stefanauto.psa;Version=3;");" in the using and worked for the first run.after the first run i still get the same error. In ur example i do not understand what sql stands for in using(SQLiteCommand cmd = new SQLiteCommand(sql, c)) – SGS Feb 18 '16 at 12:21
1

Try creating a new command;

private void test()
{
    int z;
    using (SQLiteConnection dbcon = new SQLiteConnection("Data Source=stefanauto.psa;Version=3;"))
    {
        dbcon.Open();
        using (SQLiteCommand sql = new SQLiteCommand(dbcon))
        {
            sql.CommandText = "select ID from clienti where CNP='" + cnp.Text + "'";

            z = Convert.ToInt32(sql.ExecuteScalar());


            MessageBox.Show(z.ToString());
        }

        using (SQLiteCommand sql = new SQLiteCommand(dbcon))
        {
            sql.CommandText = "insert into vandute(ID_MASINA,ID_CLIENT)values(1,2)";
            sql.ExecuteNonQuery();
        }
    }
}
Dion V.
  • 2,090
  • 2
  • 14
  • 24