“值”附近的语法不正确

本文关键字:语法 不正确 | 更新日期: 2023-09-27 18:34:15

我正在尝试使用 Windows 表单应用程序将记录添加到数据库。调试代码时,出现异常:"值"附近语法不正确很抱歉代码混乱,我是新成员。

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();
}

“值”附近的语法不正确

将值更改为值。所以:

insert into empty values("...

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

Value更改为Values

  • INSERT (Transact-SQL)

并且请使用参数化的sql。这种字符串串联对SQL注入攻击是开放的。

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();
}

使用 VALUES 而不是 Value 。一个非常常见的语法错误。