我需要在一个表中插入数据并使用添加按钮更新第二个表中的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
语句中读取?您期望什么?
也请使用参数化查询。
我可以在这里看到一些问题
using
关键字通过Dispose()方法自动清理任何对象,该方法包括SqlConnection和SqlCommand-这样可以确保在出现异常时进行适当的清理;也更容易正确编写]ExecuteNonQuery()
。正如@jdweng指出的,唯一返回记录集的查询是SELECT语句(存储过程也可能)。 Read()的含义是这段代码不清楚,我的猜测是它将始终返回false