2012-02-20 104 views
-1

我試圖插入SQL數據庫,但是我不斷收到一個錯誤錯誤插入查詢

enter image description here

下面是提到的查詢:

str2 = "Insert into [Snaps](Loc_city,Loc_state,Loc_country,Edu_Hist1,Work_Hist1) values (Loc_city= ' " + soap.data[i1].current_location.city.ToString() + "', Loc_state='" + soap.data[i1].current_location.state.ToString() + "', Loc_country='" + soap.data[i1].current_location.country.ToString() + "',Edu_Hist1='" + soap.data[i1].education_history[0].name.ToString() + "', Work_Hist1 ='" + soap.data[i1].education_history[0].school_type.ToString()+"')"; 
        cmd = new SqlCommand(str2,con); 
        cmd.ExecuteNonQuery(); 

請幫

+0

是否要更新現有字段或在表中插入新字段?你的sql是完全錯誤的。 – 2012-02-20 15:57:32

+0

我插入不更新,因爲你可以看到 – vini 2012-02-21 02:18:47

+0

布賴恩的答案就是我所說的。在更新語句中只需要'Loc_city = ...'。 – 2012-02-21 11:16:14

回答

6

你在你的值列表中不需要'Loc_city = ...'。它應該是:

str2 = "Insert into [Snaps](Loc_city,Loc_state,Loc_country,Edu_Hist1,Work_Hist1) values ('" + soap.data[i1].current_location.city.ToString() + "', '" + soap.data[i1].current_location.state.ToString() + "', '" + soap.data[i1].current_location.country.ToString() + "', '" + soap.data[i1].education_history[0].name.ToString() + "', '" + soap.data[i1].education_history[0].school_type.ToString()+"')"; 
+0

是的,它的作品謝謝! – vini 2012-02-20 16:00:47

+0

它應該改爲參數化查詢... – Pankaj 2012-02-24 02:54:13

+0

是的,我得到了那.... – vini 2012-02-24 13:52:34

3

你不需要​​的值。 Jus傳遞由逗號分隔的值

3

VALUES子句應該只包含實際數據,其插入的順序和列已經在INSERT語句中指定。

實施例:

INSERT INTO TestTable的(可樂,COLB,COLC) VALUES( 'VarcharCol',22 'VarcharColC')

2

插入值時,刪除的字段的名稱: 從:

values (Loc_city= ' " + soap.data[i1].current_location.city.ToString() + "', Loc_state='" + soap.data[i1].current_location.state.ToString() + "', Loc_country='" + soap.data[i1].current_location.country.ToString() + "',Edu_Hist1='" + soap.data[i1].education_history[0].name.ToString() + "', Work_Hist1 ='" + soap.data[i1].education_history[0].school_type.ToString()+"')"; 

要:

values ('" + soap.data[i1].current_location.city.ToString() + "', '" + soap.data[i1].current_location.state.ToString() + "', '" + soap.data[i1].current_location.country.ToString() + "', '" + soap.data[i1].education_history[0].name.ToString() + "', '" + soap.data[i1].education_history[0].school_type.ToString()+"')"; 

考慮使用SqlParameter with your SqlCommand或只是一個string.format()爲了清理查詢。