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' 附近的语法不正确。'
您的语法不正确,请确保已关闭所有打开的括号。
另外,始终使用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:命名表、列和变量时请遵循命名约定
| 归档时间: |
|
| 查看次数: |
842 次 |
| 最近记录: |