C# 数据库 SQLite 锁定数据库错误

我目前正在使用 C# 和 SQLite 编写代码。有一个错误正在抛出,指出数据库在消息框中被锁定两次。


该查询适用于 SQLite DB 浏览器,但是,当它被放置在 C# 代码中时,它会引发错误。


这是给我一个错误的代码:


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

等号似乎有问题,算术过程可能有问题。


完整代码:


 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);

        }

更新:将格式更改为using() {}但它仍然无法正常工作。程序崩溃


新代码:


   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();

            }

        }


白猪掌柜的
浏览 228回答 2
2回答

撒科打诨

问题是程序的其他部分(或其他程序)仍然有活动事务。您必须正确清理所有访问数据库的命令,即using在任何地方使用。

三国纷争

感谢所有已经回答的人。我们意识到问题在于我们从未在之前的代码中关闭阅读器。
打开App,查看更多内容
随时随地看视频慕课网APP