Sqlite Transaction,只插入最后一次插入

时间:2013-07-30 21:26:25

标签: .net sqlite system.data.sqlite

如果我在订单详细信息中插入包含多个商品的订单,则只会插入最后一个商品详情商品。

使用以下代码插入数据库

Try
    order_id = value.ID
    If order_id = 0 Then
        cmd = New SQLiteCommand(insert_order, conn)
        cmd.Parameters.AddWithValue("@customer_id", value.CustomerID)
        cmd.Parameters.AddWithValue("@status", value.Status)
        cmd.Parameters.AddWithValue("@deliver", value.Deliver)
        cmd.Parameters.AddWithValue("@created", Now.ToString("yyyy-MM-dd"))
        cmd.Parameters.AddWithValue("@deleted", "0")
        order_id = Convert.ToInt32(cmd.ExecuteScalar())
    Else
        cmd = New SQLiteCommand(update_order, conn)
        cmd.Parameters.AddWithValue("@customer_id", value.CustomerID)
        cmd.Parameters.AddWithValue("@status", value.Status)
        cmd.Parameters.AddWithValue("@deliver", value.Deliver)
        cmd.Parameters.AddWithValue("@created", Now.ToString("yyyy-MM-dd"))
        cmd.Parameters.AddWithValue("@deleted", "0")
        cmd.Parameters.AddWithValue("@id", order_id)
        cmd.ExecuteNonQuery()
        '// delete previous order details
        cmd = New SQLiteCommand(delete_order_details, conn)
        cmd.Parameters.AddWithValue("@id", order_id)
        cmd.ExecuteNonQuery()
    End If

    '// Add order details
    For Each itm As typOrderDetail In value.orderDetails
        cmd = New SQLiteCommand(insert_order_details, conn)
        cmd.Parameters.AddWithValue("@cloth_id", itm.ClothID)
        cmd.Parameters.AddWithValue("@order_id", order_id)
        cmd.Parameters.AddWithValue("@color", itm.Color)
        cmd.Parameters.AddWithValue("@desc", itm.Desc)
        cmd.Parameters.AddWithValue("@qty", itm.Qty)
        cmd.Parameters.AddWithValue("@cost", itm.Cost)
        cmd.Parameters.AddWithValue("@service_id", itm.ServiceID)
        cmd.Parameters.AddWithValue("@deleted", "0")
        cmd.ExecuteNonQuery()
    Next
    sqlTrans.Commit()
    'If bSave Then sqlTrans.Commit() Else sqlTrans.Rollback()
Catch ex As Exception
    'sqlTrans.Rollback()
    Throw
Finally

    cmd.Dispose()
    conn.Dispose()
End Try

这里是sql字符串

  

INSERT INTO订单   ([customer_id],[status],[deliver],[created],[deleted])VALUES   (@ CUSTOMER_ID,@状态,@递送,@创建,删除@);选择   last_insert_rowid();

     

INSERT INTO orders_details   ([ORDER_ID],[的service_id],[cloth_id],[DESC],[删除],[数量],[颜色],[成本])   VALUES   (@ ORDER_ID,@的service_id,@ cloth_id,@ DESC,@删除,@数量,@颜色,@成本)

请问我做错了吗?

2 个答案:

答案 0 :(得分:1)

不是100%确定这会修复它,但为所有订单详细信息保留相同的SQLiteCommand对象。在循环之外声明它,只需更新参数值并在循环中运行查询。

答案 1 :(得分:1)

看不到如何处理代码中的事务。试试这个(在C#中,抱歉):

using(SqliteTransaction tr = con.BeginTransaction()){
   foreach(var itm in value.orderDetails) {
      //construct the command, add parameters, etc.
      ...
      //link the command to the transaction
      cmd.Transaction = tr;
      //execute the command
      cmd.ExecuteNonQuery();
   }
   tr.Commit();
}