2011-04-09 124 views
2

我有這樣的代碼和它的未來與一個INSERT INTO語句錯誤...插入Access數據庫(循環)

它大概的東西,但我一直盯着它一段時間...請幫助。

'Add items to db' 
Function recordOrder() 

    objDT = Session("Cart") 

    Dim intCounter As Integer 


    For intCounter = 0 To objDT.Rows.Count - 1 

     objDR = objDT.Rows(intCounter) 

     Dim con2 As New System.Data.OleDb.OleDbConnection 

     Dim myPath2 As String 
     myPath2 = Server.MapPath("faraxday.mdb") 

     con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data source=" & myPath2 & ";" 
     Dim myCommand2 As New System.Data.OleDb.OleDbCommand 

     myCommand2.CommandText = "INSERT INTO order(order_date, coupon_id, customer_id, quantity) values('" & System.DateTime.Now & "','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) & "','" & Int32.Parse(objDR("quantity")) &"')" 
     myCommand2.Connection = con2 
     con2.Open() 
     myCommand2.ExecuteReader() 
     con2.Close() 




     test.Text += "Order ID: " & objDR("ID") & "Order Date: " & System.DateTime.Now & ", Cust ID: " & custID & ", Quantity: " & objDR("quantity") &" " 

    Next 


End Function 
+0

錯誤是什麼? – 2011-04-09 03:35:44

+0

INSERT INTO語句中的語法錯誤。 描述:執行當前Web請求期間發生未處理的異常。請查看堆棧跟蹤以獲取有關該錯誤的更多信息以及源代碼的位置。 異常詳細信息:System.Data.OleDb.OleDbException:INSERT INTO狀態的語法錯誤 – Farax 2011-04-09 03:46:53

+0

您應該打開和關閉循環外部的連接。 – 2011-04-09 03:54:22

回答

0

我想你會因爲沒有在英鎊符號內附上日期而出現錯誤。當使用變量而不是參數時,您必須在Jet(Access)中執行此操作。

VALUES(「#‘& DateTime.Now.Date &’#」,...

我也參加了這個重構的代碼爲你因爲你創造了每一個記錄是一個新的連接的自由壞消息。使用嘗試捕捉Finally塊和移動所有的東西For循環之外(請參見下文)

Function recordOrder() 

    objDT = Session("Cart") 
    Dim intCounter As Integer 
    Dim con2 As New System.Data.OleDb.OleDbConnection 
    Dim myPath2 As String 
    myPath2 = Server.MapPath("faraxday.mdb") 
    con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" <-- etc 
    Dim myCommand2 As New System.Data.OleDb.OleDbCommand 
    myCommand2.Connection = con2 
    con2.Open() 
    Try 
     For intCounter = 0 To obDT.Rows.Count - 1 
      objDR = objDT.Rows(intCounter) 
      myCommand2.CommandText = "INSERT INTO order(order_date,coupon_id,customer_id,quantity)" _ 
       & "VALUES ('#" & System.DateTime.Now.Date & "#','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) _ 
       & "','" & Int32.Parse(objDR("quantity")) & "')" 
      myCommand2.ExecuteReader() 
     Next 
    Catch ex As Exception 
     'handle errors here 
    Finally 
     If con2.State = ConnectionState.Open Then 
      con2.Close() 
     End If 
    End Try 
End Function 

記住標記爲回答如果這有助於。

+0

這些值仍未存儲在數據庫中。我不知道這個問題可能是什麼。查詢字符串是正確的... – Farax 2011-04-09 04:11:25

+0

表上的主鍵是什麼?如果您在Catch塊中放置斷點,是否會彈出任何異常?他們是什麼? – Pepto 2011-04-09 04:14:13

+0

有一個主鍵,但它的自動增量,所以我留下了空白。它不顯示任何錯誤,但不插入數據庫。 – Farax 2011-04-09 04:16:22

0

我已經整理出來的刪除單引號。感謝大家爲此做出了貢獻。