winforms - 如何更改数据表中现有行的列参数?
问题描述
我编辑了我的问题,但它仍然没有回应就关闭了。所以我从消息框里得到了建议,并用更多信息打开了另一个问题。
我在 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)....
如您所见,为了在关闭程序后保存进度,我需要在“书籍”之后添加列名。
解决方案
我了解您想要:
- 如果没有相同的行,则插入一行
BookName
,AuthorName
并且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
);
在这种情况下,唯一索引不是强制性的(但出于性能和数据一致性原因仍建议使用)
推荐阅读
- javascript - 在 Reactjs 中检测复杂对象状态变化的最简单方法是什么
- c# - 使用 Scrutor 自动进行依赖注入
- flutter - 是否有任何文本编辑器我也可以在 Flutter 的文本中间插入图像?
- shopify - 如何使用标签链接获取所有集合产品的所有标签
- ios - 如何从外围设置Corebluetooth通知的大小
- javascript - Jquery Json 值不会改变
- java - 尝试在我的组合框上使用 setConverter(),但是如果我把它放在我的初始化函数中,我会得到一个空指针异常
- regex - 如何为手机号码编写正确的正则表达式必须从特定数字或字符开始?MVC
- angular - 当我以 ISO 格式转换日期和时间时,每次我得到 000Z?
- kdb - 编写一个 Q-SQL 查询,将 BA.N 的价格乘以 2,GS.N 乘以 3,MSFT.O 乘以 4,并使用向量条件语句调用列 newPrice