【发布时间】:2019-12-06 07:31:43
【问题描述】:
我一直在尝试创建一个函数,该函数将为我的库存中缺少的所有物品设置订单。
RequiredStockForAllOrders 基本上为 stockItems 中的每个对象分配一个值,这让我知道我需要订购多少物品。
我检查了一个消息框,该消息框会更改值(ID 和数量),但是当我运行应该插入每个产品及其各自数量的循环时,我只插入 1 个产品 n 次,其中 n 是数量列表中的项目。
private void AddAllRequiredItems_Click(object sender, EventArgs e)
{
var stockItems = new List<MyData>();
//MyData is an object with a productID int and a productQuantity int
RequiredStockForAllOrders(stockItems);
//determining the quantity required for each item
OleDbConnection con = new OleDbConnection(DatabaseConnectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
con.Open();
string sql2 = "INSERT INTO restockingDetails(RestockingID,ProductID,Quantity,Shop_ID) values (@restockingID,@productID,@quantity,@shop_id)";
cmd.CommandText = sql2;
int i = 0;
while (i < stockItems.Count)
{
try
{
MessageBox.Show(stockItems[i].productId.ToString()); //For testing
cmd.Parameters.AddWithValue("@restockingID", restockingOrder);
cmd.Parameters.AddWithValue("@productID", stockItems[i].productId);
cmd.Parameters.AddWithValue("@quantity", stockItems[i].productQuantity);
cmd.Parameters.AddWithValue("@shop_id", shopIDGlobal);
cmd.ExecuteNonQuery();
MessageBox.Show(" Item added to list"); //for testing
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
i = i + 1;
}
con.Close()
}
【问题讨论】:
-
将创建命令的代码移到while循环中,我认为这就是问题所在。你不断重复使用相同的命令。
标签: c# database loops insert oledb