2015-12-02 77 views
0

當我嘗試從Visual stutio使用C#中的Access數據庫中插入數據我不斷收到此錯誤在INSERT INTO語句中的System.Data.OleDb.OleDbException:語法錯誤。 「使用C#從Visual Studio插入數據從Visual Studio的Access數據庫

保護無效Button1_Click1(對象發件人,EventArgs的) {

 Guid newGUID = Guid.NewGuid(); 

     OleDbConnection conn = new OleDbConnection(" Provider = Microsoft.ACE.OLEDB.12.0;" + "Data Source = " + Server.MapPath("App_Data/Group.accdb")); 

    OleDbCommand command = new OleDbCommand ("INSERT INTO [User] ([Userid], [UserName], [Password], [Email], [Country], [CartID], [Address]) VALUES (@Uname,@password,@email,@country,@address,@userid,@cartID)", conn); 

    conn.Open(); 
       command.Parameters.AddWithValue("@userid", Convert.ToString(newGUID)); 
       command.Parameters.AddWithValue("@Uname", username.Text); 
       command.Parameters.AddWithValue("@password", username.Text); 
       command.Parameters.AddWithValue("@email", email.Text); 
       command.Parameters.AddWithValue("@country", DropDownList1.SelectedItem.ToString()); 
       command.Parameters.AddWithValue("@cartID", Convert.ToString(newGUID)); 
       command.Parameters.AddWithValue("@address", address.Text); 
       command.ExecuteNonQuery(); 
    conn.Close(); 
      Response.Redirect("Login.aspx"); 
      Response.Write("Registration is successful");  

} 
+0

它仍然給我的錯誤 –

+0

一切在你的代碼看起來很好 - 我認爲它會起作用,這導致我相信它可能像字段名稱中的拼寫錯誤一樣簡單。你可以添加你的桌面佈局的屏幕截圖嗎? – Hambone

回答

0

用戶是保留關鍵字。您需要將它括在方括號中,就像您對字段所做的那樣:

但是,您的代碼有更嚴重的錯誤。
您的參數佔位符在字段名稱方面沒有正確的順序。所以你需要修復查詢,然後記住在OleDb中 這些參數不能被它們的名字識別,而是被它們的位置識別。 這樣的參數添加到收藏應該尊重要在其中檢索參數的順序碼值

OleDbCommand command = new OleDbCommand (@"INSERT INTO [User] 
    ([Userid], [UserName], [Password], [Email], 
     [Country], [CartID], [Address]) VALUES 
    (@userid, @Uname, @password,@email, 
     @country,@cartID, @address)", conn); 

conn.Open(); 
command.Parameters.AddWithValue("@userid", address.Text); 
command.Parameters.AddWithValue("@Uname", username.Text); 
command.Parameters.AddWithValue("@password", username.Text); 
command.Parameters.AddWithValue("@email", email.Text); 
command.Parameters.AddWithValue("@country",DropDownList1.SelectedItem.ToString()); 
command.Parameters.AddWithValue("@cartID", address.Text); 
command.Parameters.AddWithValue("@address", address.Text); 
command.ExecuteNonQuery(); 

順便說一句,你是路過的用戶名文本框到兩個用戶名字段和用戶ID和密碼。這似乎不太可能(地址文本框相同)

最後似乎也錯了使用字符串設置字段cartID和UserID的值。 AddWithValue方法無法知道將由參數更新的字段的DataType。所以它會根據值的數據類型創建一個參數。在你的情況下,address.Text和username.Text是字符串,但是如果數據庫字段期望一個整數,就會發生不好的事情。
如果是這樣的話,你應該確保你有一個整數,並使用

command.Parameters.AddWithValue("@userid", Convert.ToInt32(address.Text)); 
command.Parameters.AddWithValue("@cartID", Convert.ToInt32(address.Text)); 

在任何情況下,最好使用正確的Add方法

command.Parameters.Add("@userid", OleDbType.Integer).Value = Convert.ToInt32(address.Text)); 
+0

我做了建議的更改,但我仍然收到錯誤 –

+0

,我只使用地址框,因爲我想確保GUID不會導致問題 –

+0

請指定這些錯誤是什麼。我將向答案添加另一個潛在問題 – Steve

相關問題