首页 > 解决方案 > 如何更改数据表中现有行的列参数?

问题描述

我编辑了我的问题,但它仍然没有回应就关闭了。所以我从消息框里得到了建议,并用更多信息打开了另一个问题。

我在 Windows 窗体上的图书管理员数据库应用程序中有表,其中一列包含参数“数量”。如果 addrow SQLcommand 中的所有其他列都存在一致性,我该如何正确增加它?

这里代码:

        private void ConfimAddBookButtom_Click(object sender, EventArgs e)
        {
            string conString = "Data Source=Books.db;Version=3;";
            string name = AddBookNameTextBox.Text;
            string author = AddBookAuthorTextBox.Text;
            string genre = AddBookGenreTextBox.Text;
            int amount = 1;
            string SQLiteExpression = "insert into Books (BookName, AuthorName, Genre, Amount) values (@name, @author, @genre, @amount)";
            using (SQLiteConnection connection = new SQLiteConnection(conString))
            {
                connection.Open();
                SQLiteCommand command = new SQLiteCommand(SQLiteExpression, connection);
                SQLiteParameter nameParam = new SQLiteParameter("@name", name);
                SQLiteParameter authorParam = new SQLiteParameter("@author", author);
                SQLiteParameter genreParam = new SQLiteParameter("@genre", genre);
                SQLiteParameter amountParam = new SQLiteParameter("@amount", amount);
                command.Parameters.Add(nameParam); command.Parameters.Add(authorParam); command.Parameters.Add(genreParam); command.Parameters.Add(amountParam);
                int number = command.ExecuteNonQuery();
                connection.Close();
                MessageBox.Show("Book sucsessfuly added");
                this.Close();
            }

如你看到的。该行将始终以等于 1 的数量添加。如果其他参数一致,我需要增加现有行中的数量。

UPD。我找到了最新问题的解决方案:

INSERT OR REPLACE INTO Books (Bookname, AuthorName, Genre, amount) VALUES ( @name, @author, @genre, @amount)....

如您所见,为了在关闭程序后保存进度,我需要在“书籍”之后添加列名。

标签: winformssqlite

解决方案


我了解您想要:

  • 如果没有相同的行,则插入一行BookNameAuthorName并且Genre
  • 否则通过将数量增加指定值来更新现有行

如果您的 SQLite 版本高于 3.24.0,则可以使用UPSERT

您首先需要对定义现有行的内容创建唯一约束

CREATE UNIQUE INDEX uniquebook ON Books(BookName, AuthorName, Genre);

然后,您可以使用以下查询:

INSERT INTO Books (BookName, AuthorName, Genre, Amount)
VALUES (@name, @author, @genre, @amount)
ON CONFLIT(Bookname, AuthorName, Genre)
DO UPDATE SET amount = amount + @amount

编辑:使用旧版本的 SQlite:

INSERT OR REPLACE INTO Books (BookName, AuthorName, Genre, Amount)
VALUES (
  @name,
  @author,
  @genre,
  COALESCE((SELECT Amount FROM Books WHERE BookName = @name and AuthorName = @author AND Genre = @genre), 0) + @amount
);

在这种情况下,唯一索引不是强制性的(但出于性能和数据一致性原因仍建议使用)


推荐阅读