System.Data.SqlClient.SqlException: '关键字'values' 附近的语法不正确。'

1 c# sql-server asp.net ado.net webforms

namespace login_page
{
    public partial class itemselect : Form
    {
        public itemselect()
        {
            InitializeComponent();
        }

        private void product_Click(object sender, EventArgs e)
        {

        }

        private void Addproduct_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("Data Source=DESKTOP-QI8RJIB;Initial Catalog=itemselect;Integrated Security=True");
            con.Open();
            SqlCommand cmd = new SqlCommand(" insert into itemselect([Product ID],[Product Name],[Product Quantity],[Product Price] values ('" +pid.Text+ "','" +pn.Text+ "','" +pq.Text+ "','" +pp.Text+ "')", con);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            this.Close();
            MessageBox.Show("item added successfully");

        }
Run Code Online (Sandbox Code Playgroud)

例外:

System.Data.SqlClient.SqlException: '关键字'values' 附近的语法不正确。'

nav*_*een 5

您的语法不正确,请确保已关闭所有打开的括号。

另外,始终使用SqlParameters 来防止Sql 注入攻击并提高代码可读性

示例代码

private void Addproduct_Click(object sender, EventArgs e)
{
    string query = "INSERT INTO itemselect ([Product ID],[Product Name],[Product Quantity],[Product Price]) VALUES (@ProductID, @ProductName, @ProductQuantity, @ProductPrice)";
    using (var con = new SqlConnection(@"Data Source=DESKTOP-QI8RJIB;Initial Catalog=itemselect;Integrated Security=True"))
    using (var cmd = new SqlCommand(query, con))
    {
        // Not sure about ProductID type. Could be SqlDbType.UniqueIdentifier or SqlDbType.Int / BigInt
        cmd.Parameters.Add(new SqlParameter("@ProductID", SqlDbType.UniqueIdentifier)).Value = pid.Text;
        cmd.Parameters.Add(new SqlParameter("@ProductName", SqlDbType.NVarChar)).Value = pp.Text;
        cmd.Parameters.Add(new SqlParameter("@ProductQuantity", SqlDbType.Int)).Value = pq.Text;
        cmd.Parameters.Add(new SqlParameter("@ProductPrice", SqlDbType.Decimal)).Value = pp.Text;
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            // Records Inserted Successfully
        }
        catch (SqlException err)
        {
            // Error occured. Handle error
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

PS:命名表、列和变量时请遵循命名约定

  • Addwithvalue 显然有问题。我不希望数量或价格有文本类型。但是,是的,一定要使用参数 (2认同)
  • 好答案; 缺少一些“使用”,老实说:我强烈建议在所有“运行自己的 SQL”场景中使用 Dapper:`con.Execute(sql, new { ProductId = pid.Text, ... });` - 很多更少出错 (2认同)