首页 > 解决方案 > 更新 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);
}

标签: c#sql-servervisual-studioparameters

解决方案


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


推荐阅读