2012-07-17 256 views
0

我有一個窗體,其中我有一個組合框填充表的列名我有一個文本框,我打算輸入值,當我點擊保存按鈕時我想要的數據插入到已經選擇的各個列中。C#和SQL Server 2005連接

這是我的代碼。

private void button1_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     myConnection.ConnectionString = "Data Source = AmiayaEjay-Vaio; Initial Catalog = RealTime; User ID = sa; Password = admin"; 

     String combo1 = comboBox1.SelectedItem.ToString(); 
     String combo2 = comboBox2.SelectedItem.ToString(); 
     String combo3 = comboBox3.SelectedItem.ToString(); 
     String combo4 = comboBox4.SelectedItem.ToString(); 
     String combo5 = comboBox5.SelectedItem.ToString(); 
     String combo6 = comboBox6.SelectedItem.ToString(); 
     String combo7 = comboBox7.SelectedItem.ToString(); 
     String combo8 = comboBox8.SelectedItem.ToString(); 

     query1.CommandText = "insert into dbo.DepthTable ('" + combo1 + "','" + combo2 + "','" + combo3 + "','" + combo4 + "','" + combo5 + "','" + combo6 + "' ,'" + combo7 + "','" + combo8 + "') values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')"; 

     query1.CommandType = CommandType.Text; 
     query1.Connection = myConnection; 

     myConnection.Open(); 
     query1.ExecuteNonQuery(); 
    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 

    myConnection.Close(); 
} 

我不斷獲取我有無效的列名的錯誤消息,因爲SQL命令不能看到COMBO1-combo8有一個有效的列名

+0

您確定來自組合框的文本有有效的列名嗎?也許嘗試在查詢中將方括號中的列名稱包裝起來? – Ken 2012-07-17 15:35:28

+8

請做一些關於SQL注入攻擊的研究! – 2012-07-17 15:36:23

+0

您不需要列列表中的單引號,也可以在字符串變量中創建字符串以查看該值是什麼,然後根據數據庫架構驗證該字符串... var query =「insert .... 。「 query1.CommandText = query; – christiandev 2012-07-17 15:54:53

回答

3

去掉「'」在COMBOX跡象。

"insert into dbo.DepthTable (" + combo1 + "," + combo2 + "," + combo3 + "," + combo4 + "," + combo5 + "," + combo6 + "," + combo7 + "," + combo8 + ") values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "')"; 
+0

我試過這樣做,但是查詢沒有看到combo1的值爲combo8爲列名,所以插入失敗 – 2012-07-17 15:51:17

+1

你怎麼知道的?也許列名是不正確的。嘗試調試並提取查詢文本並在sql server management studio中運行它。有錯誤嗎? – 2012-07-17 15:58:49

+0

@Amiran我不能查詢SQL服務器上的腳本,因爲它是一個窗口窗體,我已經輸入組合框和文本框,我試圖使用try和catch異常來調試 – 2012-07-17 16:10:42