Nora
Nora

Reputation: 56

C# Databases SQLite Locked Database Error

I am currently writing a code using C# and SQLite. There is an error being throwing stating that the database is locked twice in a message box.

The query works on SQLite DB Browser however, when it is placed in C# code it throws the error.

Here is the code that is giving me an error:

cmd.CommandText = "UPDATE customers SET Bill = Bill - "+textBox2.Text+" WHERE customers.CustomerID = " + textBox1.Text + ";";

There seems to be an issue with the equals sign, might be something wrong with the arithmetic process.

Complete code:

 SQLiteConnection myconn = new SQLiteConnection(@"Data Source = C:\Users\chick\Newspaper.db");
        SQLiteCommand cmd = myconn.CreateCommand();
        cmd.CommandText = "UPDATE customers SET Bill = (Bill - "+textBox2.Text+") WHERE customers.CustomerID = " + textBox1.Text + ";";
        myconn.Open();
        try
        {
            cmd.ExecuteNonQuery();
            MessageBox.Show("Succesfully Update");
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

UPDATE: Changed format to using() {} however it is still not working. Program is crashing

New Code:

   using (SQLiteConnection myconn = new SQLiteConnection(@"Data Source = C:\Users\chick\Newspaper.db"))
        {

            var sql = "Update customers SET Bill = Bill - @pay WHERE customers.CustomerID = @cid;";
            myconn.Open();
            using (var cmd = new SQLiteCommand(sql, myconn))
            {
                cmd.Parameters.AddWithValue("@cid", textBox1.Text);
                cmd.Parameters.AddWithValue("@pay", textBox2.Text);
                cmd.ExecuteNonQuery();
            }
        }

Upvotes: 0

Views: 109

Answers (2)

Nora
Nora

Reputation: 56

Thank you to all that have answered. We realized the issue was that we never closed the reader in previous code.

Upvotes: 0

CL.
CL.

Reputation: 180240

The problem is that some other part of the program (or some other program) still has an active transaction.

You must properly clean up all commands that access the database, i.e., use using everywhere.

Upvotes: 1

Related Questions