我正在尝试更新两个表的值,例如从dataGridview 订单表和Orderdetail表,如我的图片所示。
它正在更新Order表,但无法更新OrderdDetail表。我想用相同的OrderNr更新所有行。我从dataGridView获取OrderDetail值。这是我的代码:
private void UpdateOrder(int paymentTypes)
{
try
{
string connstring = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("UPDATE [Orders] SET Amount = @Amount, Tax = @Tax , ToPay = @ToPay WHERE OrderNr = @OrderNumber", conn))
{
// This First table Orders updating fine
cmd.Parameters.AddWithValue("@Amount", txtAmount.Text);
cmd.Parameters.AddWithValue("@Tax", txtTax.Text);
cmd.Parameters.AddWithValue("@ToPay", txtToPay.Text);
cmd.ExecuteNonQuery();
}
// Here begin for OrderDetails table and not working to update.
foreach (DataGridViewRow row in dgvCart.Rows)
{
using (OleDbCommand cmd = new OleDbCommand("UPDATE [OrdersItems] SET OrderNr = @OrderNumber, ProductId = @ProductId, Quantity = @Quantity, WHERE OrderNr = @OrderNumber AND ProductId = @ProductId", conn))
{
cmd.Parameters.AddWithValue("@Quantity", Convert.ToInt32(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("@OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("@ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Updating successfully !", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
答案 0 :(得分:0)
您的代码中有几个错误。
首先,您在查询中遇到语法错误
using (OleDbCommand cmd = new OleDbCommand(@"UPDATE [OrdersItems]
SET OrderNr = @OrderNumber, ProductId = @ProductId, Quantity = @Quantity,
WHERE OrderNr = @OrderNumber AND ProductId = @ProductId", conn))
您应删除WHERE语句之前的逗号。
第二,第一个查询缺少OrderNumber的参数。
第三点。 在OleDb参数中,参数是位置性的,即使您可以命名它们,也应按照它们在查询中出现的顺序放置它们,并且如果两次使用它们,则需要再次放置它(OrderNumber和ProductID都出现在SET部分中并在哪里)
cmd.Parameters.AddWithValue("@OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("@ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));
cmd.Parameters.AddWithValue("@Quantity", Convert.ToInt32(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("@OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("@ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));
但是,您不需要更新ProductID和OrderNumber。它们无法更改,否则此查询将找不到您要更新的行。
using (OleDbCommand cmd = new OleDbCommand(@"UPDATE [OrdersItems]
SET Quantity = @Quantity
WHERE OrderNr = @OrderNumber AND ProductId = @ProductId", conn))
只有三个参数以正确的顺序
cmd.Parameters.AddWithValue("@Quantity", Convert.ToInt32(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("@OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("@ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));