c# - 更新 SQL 数据库似乎可以工作,但没有更改数据
问题描述
我从 C# 开始,并且正在制作一个工具来更新表中的字段,当 box_id 位于文本框中并单击按钮时。我已经解决了许多错误,现在一切都没有错误,但没有数据被更改。对这个问题的任何帮助将是一个很大的帮助。
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
string query = @"UPDATE Shipment_SCK
SET printed = '1'
WHERE box_id IN (@textBox1);";
SqlCommand cmd = new SqlCommand(query, conn);
Form1 a = new Form1();
cmd.Parameters.Add("@textBox1", SqlDbType.VarChar, 7).Value = a.textBox1.Text;
conn.Open();
int rowsaffected = cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show(rowsaffected.ToString() + " Shipments updated");
}
}
catch (Exception ex)
{
MessageBox.Show("Unable to update:" + ex.Message);
}
解决方案
At this lines:
Form1 a = new Form1();
cmd.Parameters.Add("@textBox1", SqlDbType.VarChar, 7).Value = a.textBox1.Text;
You're instantiating a new Form1
instance, maybe you can't update nothin' due to empty values on your IN
statement. I don't know your logic and how data comes to the method, but maybe you can do something like this:
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
string boxIds = "134, 593, 333, 666";
string query = $@"UPDATE Shipment_SCK
SET printed = '1'
WHERE box_id IN ({boxIds});";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
int rowsaffected = cmd.ExecuteQuery();
conn.Close();
MessageBox.Show(rowsaffected.ToString() + " Shipments updated");
}
}
catch (Exception ex)
{
MessageBox.Show("Unable to update:" + ex.Message);
}
Where boxIds
its a string containing all the IDs to be used in your query.
Kind regards
推荐阅读
- cs50 - CS50 复数问题,错误:使用未声明的标识符“i”
- r - 将来自 for 循环的多个 ggplots 保存在特定布局中的单个图中
- python-3.x - 即使手动工作,Selenium 也无法单击表格行
- docker - 可以在容器到容器之间共享文件夹吗?
- php - 如何通过属性值 PhP 对 xml 子项进行排序
- javascript - Firestore 上的条件 where 查询
- apache-kafka - Kafka 消费者需要时间来识别新分区
- javascript - 组件未呈现(ReactJS/MaterialUI)
- mongodb - mongodb 汇总数据列与总计
- html - REST API 是否应该设置 cookie