使用参数编写查询以避免SQL注入

时间:2015-08-11 15:49:37

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

之前我已经这样做了,但在这种情况下,我有一个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格式是否正确。

感谢的

1 个答案:

答案 0 :(得分:0)

试试这个:

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