'value'附近的语法不正确

时间:2013-10-05 20:15:38

标签: c# sqlconnection

我正在尝试使用Windows Form Application向DB添加记录。 当我调试代码时,我得到一个例外:'value'附近的语法不正确 对不起代码中的混乱,我是新成员。

private void button1_Click(object sender, EventArgs e)
{
     SqlConnection con = new SqlConnection("Data Source=.\\sqlexpress;Initial   Catalog=VirtualSalesFair;Integrated Security=True");
     con.Open();
     SqlCommand sc = new SqlCommand("Insert into Empty value('" + textBox1.Text + "'," + textBox2.Text + ",'" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "','" + textBox8.Text + "','" +textBox9.Text +"',"+textBox10.Text +");", con);
     int o=sc.ExecuteNonQuery();
     MessageBox.Show(o+ ":Record has been inserted");
     con.Close();
}

3 个答案:

答案 0 :(得分:3)

将您的Value更改为Values

请使用 parameterized sql 。这种字符串连接对SQL Injection攻击开放。

using(SqlConnection con = new SqlConnection("Data Source=.\\sqlexpress;Initial   Catalog=VirtualSalesFair;Integrated Security=True"))
{
   con.Open();
   SqlCommand sc = new SqlCommand("INSERT INTO Empty VALUES(@VAL1, @VAL2, @VAL3, @VAL4, @VAL5, @VAL6, @VAL7, @VAL8, @VAL9, @VAL10)", con);
   sc.Parameters.AddWithValue("@VAL1", textBox1.Text);
   sc.Parameters.AddWithValue("@VAL2", textBox2.Text);
   sc.Parameters.AddWithValue("@VAL3", textBox3.Text);
   sc.Parameters.AddWithValue("@VAL4", textBox4.Text);
   sc.Parameters.AddWithValue("@VAL5", textBox5.Text);
   sc.Parameters.AddWithValue("@VAL6", textBox6.Text);
   sc.Parameters.AddWithValue("@VAL7", textBox7.Text);
   sc.Parameters.AddWithValue("@VAL8", textBox8.Text);
   sc.Parameters.AddWithValue("@VAL9", textBox9.Text);
   sc.Parameters.AddWithValue("@VAL10", textBox10.Text);

   int o = sc.ExecuteNonQuery();
   MessageBox.Show(o + ":Record has been inserted");
   con.Close();
}

答案 1 :(得分:3)

将值更改为值。所以:

insert into empty values("...

这是插入行的正确SQL语法。

答案 2 :(得分:2)

使用VALUES代替Value。一个非常常见的语法错误。