【发布时间】:2021-08-24 19:18:32
【问题描述】:
我有一个 Access 数据库。我正在使用 C# 和 Visual Studio 我试图在事务中插入几行。但是,我没有插入每一行,而是将第一个元素插入了多次。
我可以一次将数据插入“发票”表中的一行,因此该表处于正常工作状态。我包括下面的代码。这些行确实有不同的数据。调试器显示。
private void insertInvoiceItemsIntoDatabase(int tableNumber)
{
string category, food;
double price
string connectionString = _databaseConnectionString;
using (OleDbConnection connection =
new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand();
OleDbTransaction transaction = null;
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the transaction.
try
{
connection.Open();
// Start a local transaction with ReadCommitted isolation level.
transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
command.Connection = connection;
command.Transaction = transaction;
command.CommandText = "Insert into Invoices (TableNumber, Category, Food, Price) VALUES (?,?,?,?)";
command.CommandType = CommandType.Text;
Order order;
order = tables[tableNumber - 1].getOrder();
List<MenuItem> items = order.deepCopyMenuItems();
for (int i = 0; i < items.Count(); i++)
{
FoodType ft = items[i].getFoodType();
category = "Main Course";
if(ft == FoodType.maincourse)
{
category = "Main Course";
}else if(ft == FoodType.drink)
{
category = "Drink";
}else if(ft == FoodType.dessert)
{
category = "Dessert";
}
food = items[i].getItemName();
price = items[i].getItemPrice();
command.Parameters.AddWithValue("TableNumber", tableNumber);
command.Parameters.AddWithValue("Category", category);
command.Parameters.AddWithValue("Food", food);
command.Parameters.AddWithValue("Price", price);
command.ExecuteNonQuery();
}
transaction.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
try
{
// Attempt to roll back the transaction.
transaction.Rollback();
}
catch
{
// Do nothing here; transaction is not active.
}
}
}
}
【问题讨论】:
-
您正在使用单个命令并反复向其添加相同的参数。只需在
for循环的每次迭代中创建一个新的OleDbCommand。 -
停止使用 AddWithValue() dbdelta.com/addwithvalue-is-evil
-
@OlivierRogier 在这种情况下不是。 Alejandro 的解决方案奏效了。
-
@Alejandro -- 谢谢!这为我解决了问题。