我有一個窗體,其中我有一個組合框填充表的列名我有一個文本框,我打算輸入值,當我點擊保存按鈕時我想要的數據插入到已經選擇的各個列中。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有一個有效的列名
您確定來自組合框的文本有有效的列名嗎?也許嘗試在查詢中將方括號中的列名稱包裝起來? – Ken 2012-07-17 15:35:28
請做一些關於SQL注入攻擊的研究! – 2012-07-17 15:36:23
您不需要列列表中的單引號,也可以在字符串變量中創建字符串以查看該值是什麼,然後根據數據庫架構驗證該字符串... var query =「insert .... 。「 query1.CommandText = query; – christiandev 2012-07-17 15:54:53