System.Data.SqlClient.SqlException:'关键字'values'附近的语法不正确。'
c#
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");
}
例外:
System.Data.SqlClient.SqlException: '关键字'values' 附近的语法不正确。'
回答
您的语法不正确,请确保已关闭所有打开的括号。
另外,始终使用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
}
}
}
PS:命名表、列和变量时请遵循命名约定
- Addwithvalue apparently has issues. And I don't expect quantity or price to have a text type. But yes, DO use parameters
- Good answer; missing a few `using`s, and honestly: I'd strongly advocate Dapper in all "running own SQL" scenarios: `con.Execute(sql, new { ProductId = pid.Text, ... });` - much less to get wrong
THE END
二维码