这个问题在这里已有答案:
我正在将一个字符串或数字传递给SQL查询。
单引号的含义是什么,双引号内的单引号是什么?
select * from college where class = '"+txtclass.Text+"'
要么
select * from college where class = '+txtclass.Text+'
您应该使用SqlCommand的参数。
这里有一个关于如何做的小例子:
using (var con = new SqlConnection("conection string"))
{
con.Open();
using (var cmd = con.CreateCommand())
{
// Here is where we add the parameters into the Sql Query, this way it will prevent SQL Injection
cmd.CommandText = "select * from college where class = @class";
// Now we add the value to the parameter @class, I'm assuming here that the column class is a NVarchar
cmd.Parameters.Add("@class", SqlDbType.NVarChar).Value = txtclass.Text;
using (var dr = cmd.ExecuteReader())
{
while (dr.Read())
{
// Do some code
}
dr.Close();
}
}
}
这个例子是针对Sql的,但是同样可以对MySql做,我们只需要使用MySql类,其余的都是一样的
注意:我知道这不能回答已经提出的问题,但由于他的工作方式存在安全风险,我决定举一个简单的例子来说明如何使其更安全,因为答案已经给出了对这个问题的评论