如何在查询中引用表单元素的值? C# 数据库
How do I refer to my form elements' values in a query? C# MSSQL
我正在尝试将数据从我的文本框值插入到数据库中。
这段代码工作得很好
SqlCommand query = new SqlCommand(@"INSERT INTO GuestTable (CustomerName, Address) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "')", con);
但我只需要将该数据插入指定的ID。所以我想我需要添加这个:
WHERE CustomerID = '" +Convert.ToInt32(textBox3.Text)+"'
但是只有在我 运行 程序说“Error near 'WHERE' keyword..”
之后,该行才会出现错误
总之,你不是那样做的。您永远不应在 SQL 查询中使用字符串连接。在 C# 中,您应该使用参数化查询。然后,您可以使用 C# 提供的方法将您的变量插入到查询中。
这是取自 Using Parameterized Query to Avoid SQL Injection
的示例
string sql = "select count(UserID) from user_login where UserID=@UserID and pwd=@pwd";
SqlCommand cmd = new SqlCommand(sql, con);
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@UserID", txtUSerID.Text);
param[1] = new SqlParameter("@pwd", txtPwd.Text);
cmd.Parameters.Add(param[0]);
cmd.Parameters.Add(param[1]);
我正在尝试将数据从我的文本框值插入到数据库中。 这段代码工作得很好
SqlCommand query = new SqlCommand(@"INSERT INTO GuestTable (CustomerName, Address) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "')", con);
但我只需要将该数据插入指定的ID。所以我想我需要添加这个:
WHERE CustomerID = '" +Convert.ToInt32(textBox3.Text)+"'
但是只有在我 运行 程序说“Error near 'WHERE' keyword..”
之后,该行才会出现错误总之,你不是那样做的。您永远不应在 SQL 查询中使用字符串连接。在 C# 中,您应该使用参数化查询。然后,您可以使用 C# 提供的方法将您的变量插入到查询中。
这是取自 Using Parameterized Query to Avoid SQL Injection
的示例string sql = "select count(UserID) from user_login where UserID=@UserID and pwd=@pwd";
SqlCommand cmd = new SqlCommand(sql, con);
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@UserID", txtUSerID.Text);
param[1] = new SqlParameter("@pwd", txtPwd.Text);
cmd.Parameters.Add(param[0]);
cmd.Parameters.Add(param[1]);