首页 > 解决方案 > SDA.SelectCommand.ExecuteNonQuery(); System.Data.SqlClient.SqlException:''{' 附近的语法不正确。'

问题描述

这是发生错误的快照,我不知道我做错了什么:

在此处输入图像描述

private void Form1_Load(object sender, EventArgs e)
{
    con.Open();
    String query = "INSERT INTO STOCK_IN { SIN_No., PO_NO., Product_ID, Received_Date, Quantity } VALUES ('"+textBox1.Text+ "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')";

    SqlDataAdapter SDA = new SqlDataAdapter(query , con);
    SDA.SelectCommand.ExecuteNonQuery();
    con.Close();

    MessageBox.Show("DATA INSERTED SUCCESSFULLY");
}

标签: c#sql-serverwinforms

解决方案


花括号是不正确的语法。也尝试这样的事情来处理这个插入和捕获错误。在 SIN_NO 之后还有一个尾随句点,我不知道这是您的列名的一部分还是错字。

private void Form1_Load(object sender, EventArgs e)
{
    String query = "INSERT INTO STOCK_IN(SIN_No., PO_NO., Product_ID, Received_Date, Quantity) VALUES (@val1, @val2, @val3, @val4, @val5)";

    SqlDataAdapter sda = new SqlDataAdapter();

    try
    {
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            con.Open();
            cmd.Parameters.Add("@val1", SqlDbType.VarChar).Value = textBox1.Text;
            //Then the same for 2, 3, 4, 5

            sda = cmd.ExecuteNonQuery();
        }
    }
    catch (SqlException ex) 
    {
         Console.WriteLine(ex.Message); 
    }
    finally 
    { 
         con.Close(); 
         MessageBox.Show("DATA INSERTED SUCCESSFULLY"); 
    }
}

推荐阅读