2016-05-13 59 views
0

我是使用sqlserver的新手,我試圖將選中的組合框的值插入到表中。我的代碼如下所示:C#通過sqlcommand插入組合框數據

SqlConnection con = new SqlConnection("connection string here"); 
... 

con.Open(); 
SqlCommand cmd = new SqlCommand(@"INSERT INTO Accounts 
           (server) 
           VALUES ('" + comboBox1.SelectedItem.ToString() + "'", con); 

cmd.ExecuteNonQuery(); 
con.Close(); 
MessageBox.Show("Data inserted."); 

我收到錯誤消息說: enter image description here

OCE從comboBox1 BTW的項目。它工作正常,當我把textBox.Text等,但現在這裏有什麼錯?感謝您的閱讀! :)

回答

2

您在查詢VALUES()失蹤)

SqlCommand cmd = new SqlCommand(@"INSERT INTO Accounts 
           (server) 
           VALUES ('" + comboBox1.SelectedItem.ToString() + "')", con); 

,但我建議你使用的參數,以避免SQL注入,像這樣:

SqlCommand cmd = new SqlCommand(@"INSERT INTO Accounts (server) VALUES (@server)", con); 
cmd.Parameters.AddWithValue("@server", comboBox1.SelectedItem.ToString()); 
cmd.ExecuteNonQuery(); 
+0

好點:) +1主要用於指出SQL注入漏洞 - 我的一個寵物討厭 –

+0

@GeoffJames謝謝! –

+0

謝謝你的回答!我甚至對我提出這樣一個愚蠢的問題感到抱歉。感謝您的建議!祝你有個愉快的日子:) –