有两个表 customer_invoice 和 sold_item_details
这是我对代码的抽象视图,
public void txtRent_PreviewKeyDown(object sender, KeyEventArgs e){
/* This method will Insert values to the customer_invoice table */
CreateOrder();
/* This method will Insert values to the sold_item_details table*/
InsertOrderItem(OrderItem orderItem);
}
这是我的问题,当执行插入查询时,第二个查询引发了一个无法添加或更新子行的MysqlException。我在 CreateOrder()和InserOrderItem()之间签入了强烈>插入过程是否已经令人惊讶地完成,结果证明它已成功。
例如,如果我使用 cus_inv_id = 1 插入值设置,则会将其插入 customer_invoice 表中,但在插入 sold_item_details 表时 cus_inv_id(FK)= 1 会引发该异常。
这两个与这两种方法相关的代码。 (为了解决问题,我删除了一些列)
public void CreateOrder()
{
_connection.open();
var mysqlTrans = _connection.BeginTransaction();
var orderId = -1;
MySqlDataReader sqlDataReader;
try
{
const string query =
"SELECT cus_inv_id FROM customer_invoice " +
"WHERE customer_id = @cusId";
var mysqlCommand1 = new MySqlCommand(query, _connection, mysqlTrans);
mysqlCommand1.Parameters.AddWithValue("@cusId", customerId);
sqlDataReader = mysqlCommand1.ExecuteReader();
if (sqlDataReader.HasRows)
{
sqlDataReader.Read();
orderId = (int) sqlDataReader["cus_inv_id"];
}
sqlDataReader.Close();
if (orderId == -1)
{
var mysqlCommand2 = _connection.CreateCommand();
mysqlCommand2.Connection = _connection;
mysqlCommand2.Transaction = mysqlTrans;
mysqlCommand2.CommandText = "SELECT MAX(cus_inv_id) FROM customer_invoice " +
"HAVING MAX(cus_inv_id) IS NOT NULL";
sqlDataReader = mysqlCommand2.ExecuteReader();
if (sqlDataReader.Read())
{
orderId = (int) sqlDataReader["MAX(cus_inv_id)"] + 1;
}
else
{
orderId += 2;
}
sqlDataReader.Close();
mysqlCommand2.CommandText =
"INSERT INTO customer_invoice(cus_inv_id)" +
" VALUES(@cusInvId)";
mysqlCommand2.Parameters.AddWithValue("@cusInvId", orderId);
mysqlCommand2.ExecuteNonQuery();
}
mysqlTrans.Commit();
_connection.close();
}
catch (Exception ex)
{
MessageBox.Show(ex);
mysqlTrans.Rollback();
}
}
public void InsertOrderItem(OrderItem orderItem)
{
_connection.open();
var mysqlCommand = _connection.CreateCommand();
var mysqlTrans = _connection.BeginTransaction();
mysqlCommand.Connection = _connection;
mysqlCommand.Transaction = mysqlTrans;
try
{
mysqlCommand.CommandText = "SELECT MAX(sold_item_id) FROM sold_item_details " +
"HAVING MAX(sold_item_id) IS NOT NULL";
var sqlDataReader = mysqlCommand.ExecuteReader();
var lastSoldItemId = 1;
if (sqlDataReader.Read())
{
lastSoldItemId = (int) sqlDataReader["MAX(sold_item_id)"] +1;
}
sqlDataReader.Close();
mysqlCommand.CommandText = "INSERT INTO sold_item_details(sold_item_id,cus_inv_id) VALUES(@soldItemId, @cusInvId)";
mysqlCommand.Parameters.AddWithValue("@soldItemId", lastSoldItemId);
mysqlCommand.Parameters.AddWithValue("@cusInvId", orderItem.OrderId);
mysqlCommand.ExecuteNonQuery();
mysqlTrans.Commit();
_connection.close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
mysqlTrans.Rollback();
}
}