【问题标题】:Writing query with parameters to avoid SQL Injections使用参数编写查询以避免 SQL 注入
【发布时间】:2015-08-11 15:49:37
【问题描述】:

我以前做过,但在这种情况下,我有一个insert into table 查询,其中目标表的列的值来自另一个查询的结果。有了这个,我不确定我的parametarized query 的格式是否正确。

这是一个没有Sql Injection之前的原始查询修复:

cmd.CommandText += "insert into controlnumber (controlnumber, errorid) 
values ('" + ControlNumber + "', (select errorid from error where 
errordescription = '" + ErrorDescription + "' and errortype = '" + 
ErrorType + "' + and applicationid = " + ApplicationID + " and statusid =
" + StatusID + " and userid = " + UserID + " and errortime = '" + 
ErrorTime + "');";

这是我尝试修复Sql Injection后的查询:

cmd.CommandText = "insert into ControlTable(ControlNumber, ErrorID)
values (@ControlNum, (select errorid from error where errordescription = 
@ErrorDescription and errortype = @errorType and applicationid = 
@ApplicationID and statusid = @StatusID and userid = @UserID and 
errortime = @ErrorTime)"

这是我添加参数的地方:

.....

command.CommandType = CommandType.Text
command.Parameters.AddWithValue("@ErrorDescription ", ErrorDesc);
command.Parameters.AddWithValue("@ControlNum", cntNumber);
command.Parameters.AddWithValue("@errorType",ErrorType);
command.Parameters.AddWithValue("@ApplicationID",AppID);
command.Parameters.AddWithValue("@StatusID",StatusID);
command.Parameters.AddWithValue("@UserID",UserID);

.... 我只是想知道我的CommandText 的格式是否正确。

谢谢

【问题讨论】:

    标签: sql-injection parameterized sql-parametrized-query


    【解决方案1】:

    试试这个:

    cmd.CommandText = "insert into ControlTable(ControlNumber, ErrorID)
    select @ControlNum, errorid from error where errordescription = 
    @ErrorDescription and errortype = @errorType and applicationid = 
    @ApplicationID and statusid = @StatusID and userid = @UserID and 
    errortime = @ErrorTime)"
    

    当使用 INSERT INTO SELECT FROM 时,不要使用关键字 VALUES。语法是:

    INSERT INTO TABLE(columns) SELECT ... FROM TABLE2
    

    【讨论】:

    • 谢谢,但就我而言,我不使用INSERT INTO TABLE(columns) SELECT ... FROM TABLE2,我的第二列是select语句的结果
    • 我怀疑这会奏效。您很可能需要将第一列值合并到您的选择中
    • @ElenaDBA 是也不是。如果error 中匹配的项目数can 起作用(假设ControlTable 允许ErrorID 的空值 - 否则匹配计数必须== 1)。如果匹配数 > 1,则始终失败。
    猜你喜欢
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    • 2015-11-05
    相关资源
    最近更新 更多