SQL select参数包含撇号

Nez*_*zir -5 c# sql sql-server parameters

我有问题productName参数,其中包含字符串Acreditors buye's something,在这种情况下,我只需要检查db中是否存在productname和SKU.

我收到了错误

's'附近的语法不正确.
字符串''后面的未闭合引号.

我尝试了一些逃避字符的东西,也使用了类似但没有作品.

这是我的代码:

String query = "SELECT * FROM " + toDB + ".dbo.Products WHERE Name like '" + productName.Replace("'","\'") + "' and SKU='" + newSKU+"'";

SqlConnection c = new SqlConnection(cs);
SqlCommand command = new SqlCommand(query, c);
c.Open();
object o = (object)command.ExecuteScalar();
c.Close();
Run Code Online (Sandbox Code Playgroud)

这只是我对SQL注入感到惊讶的样本

非常感谢您帮助我:这是实际上工作的代码:

        string commandText = "SELECT * FROM " + toDB + ".dbo.Product WHERE Name= @prodName and SKU=@sku;";

        using (SqlConnection c = new SqlConnection(cs))
        {
            SqlCommand command = new SqlCommand(commandText, c);
            command.Parameters.Add("@prodName", SqlDbType.VarChar);
            command.Parameters["@prodName"].Value = productName;

            command.Parameters.Add("@sku", SqlDbType.VarChar);
            command.Parameters["@sku"].Value = newsku;

            c.Open();
            object o = (object)command.ExecuteScalar();
            c.Close();
            if (o != null)
                result = true;
        } 
Run Code Online (Sandbox Code Playgroud)

Hab*_*bib 5

您应该使用参数进行查询,然后您不需要转义特殊字符,例如:

using (SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder())
{
    toDB = sqlCommandBuilder.QuoteIdentifier(toDB);
}


string query = "SELECT * FROM " + toDB + ".dbo.Products WHERE Name like @productName and SKU = @SKU";

using (SqlConnection c = new SqlConnection(cs))
using (SqlCommand command = new SqlCommand(query, c))
{
    c.Open();
    command.Parameters.Add(new SqlParameter("@productName", SqlDbType.VarChar) { Value = productName });
    command.Parameters.Add(new SqlParameter("@SKU", SqlDbType.VarChar) { Value = SKU });
    //or command.Parameters.AddWithValue("@productName", productName);

    object o = (object)command.ExecuteScalar();
}
Run Code Online (Sandbox Code Playgroud)

由于您正在使用toDB (可能来自用户输入),您应该转义,使用SqlCommandBuilder.QuoteIdentifier,因为您无法传递表名/列名等的参数.

还有一件事是使用using语句与那些实现IDisposable接口的对象.如果是SqlConnection,将语句括起来using将确保在范围结束时关闭连接.在上述情况下,即使出现异常,连接也会在执行命令后关闭.

用于创建SQL查询的字符串连接对SQL注入是开放的.阅读有关SQL注入的更多信息,并参阅SQL注入攻击预防:我从哪里开始