如何通过一个连接 运行 两个 SQL 命令?

How can I run two SQL commands with a single connection?

我需要在一个 table 中插入数据并在第二个 table 中使用添加按钮更新 ID:

private void addButton_Click(object sender, EventArgs e)
{
    con.Open();
    cmd = new SqlCommand("Insert Into Rent(toolId, customerId, custName, Fee, date, dueDate) Values('" + toolIdComboBx.Text + "', '" + custIdTxtBx.Text + "', '" + custNameTxtBx.Text + "', '" + feeTxtBx.Text + "', '" + dateTimePicker2.Text + "', '" + dateTimePicker1.Text + "')", con);

    dr = cmd.ExecuteReader();

    if (dr.Read())
    {
        con.Close();
        con.Open();

        cmd = new SqlCommand("Update Inventory Set Available = 'No' Where ToolId =  = '" + toolIdComboBx.Text + "' ");

        cmd.ExecuteNonQuery();
    }

    con.Close();
    DisplayData();
}

如果连接打开 SqlDataReader,则无法关闭连接。

为什么要阅读 INSERT 语句?你期待什么?

此外,使用参数化查询。

更新

INSERT 没有结果值,因此请改用 ExecuteNonQuery()。这样,连接可用于下一个 SqlCommand

我可以在这里看到一些问题

  1. 永远,永远,永远使用参数化查询(@broots-waymb 的支持),永远不要将用户输入连接到 SQL 命令中
  2. 使用 using 关键字通过 Dispose() 方法自动清理任何对象,包括 SqlConnection 和 SqlCommand - 这确保在出现异常时进行正确清理;也更容易正确书写
  3. 如果您不希望对记录集进行 return 编辑,请使用 ExecuteNonQuery()。正如@jdweng 指出的,returns 记录集的唯一查询是 SELECT 语句(存储过程也可能)。 Read() 的意思是这段代码不清楚,我的猜测是它总是 return false
  4. 当您的数据库模式包含一个 table(库存),其状态依赖于另一个 table(租金)的状态时,请小心。考虑避免这种情况的策略,但如果不能,则应考虑将更新包装到数据库事务中的两个 table,以确保系统状态一致

谢谢大家!我想通了

con.Open();

        using (cmd = new SqlCommand("Insert Into Rent(toolId, customerId, custName, 

费用、日期、截止日期)值('" + toolIdComboBx.Text + "', '" + custIdTxtBx.Text + "', '" +

custNameTxtBx.Text + "', '" + feeTxtBx.Text + "', '" + dateTimePicker2.Text + "', '" +

dateTimePicker1.Text + "')", con))

        {
            cmd.ExecuteNonQuery();
        }

        using (cmd = new SqlCommand("Update Inventory Set Available = 'No' Where ToolId  = '" + toolIdComboBx.Text + "' ", con))

        {
            cmd.ExecuteNonQuery();
        };

        con.Close();

        DisplayData();