有人可以告诉我为什么以下代码在字符串之前和之后添加2个单引号(''string'')?
List<string> rolls
StringBuilder sb = new StringBuilder();
foreach (var roll in rolls)
sb.Append("'" + roll + "',");
string rollList = sb.ToString().TrimEnd(',');
string sql =
@"SELECT enrolment_status, roll_number FROM dt_modular_enrolment WHERE id_student = ?
AND roll_number in " + "( " + rollList + " )";
creates the below:
in ( ''ROLL4'',''ROLL6'',''ROLL5'',''ROLL1'',''ROLL2'',''ROLL3'' )
谢谢!
只是为了更新 - 代码没有任何问题(除了sql注入的可能性),它是一个添加额外引号的sql profiler bug。
答案 0 :(得分:3)
从SQL注入的角度来看,这实际上非常危险。不幸的是,IN
查询非常难以正确参数化,因为TSQL缺少“拆分”功能。但是,很多工具可以帮助您解决这个问题。例如,对于大多数LINQ提供程序,它只是:
List<string> rolls = ...
int studentId = ...
var query = from row in ctx.ModularEnrolment
where row.StudentId = studentId
and rolls.Contains(row.roll_number)
select new { row.EnrolmentStatus, row.RollNumber };
或使用dapper之类的工具(如果没有使用括号,则会对in @someParameter
进行特殊处理):
List<string> rolls = ...
int studentId = ...
var rows = connection.Query(@"
SELECT enrolment_status, roll_number FROM dt_modular_enrolment
WHERE id_student = @studentId and roll_number in @rolls",
new { rolls, studentId });
答案 1 :(得分:2)
确保在滚动列表字符串中不包含引号
答案 2 :(得分:0)
不要在那里弄乱,而是使用用于连接的连接方法 列表中的所有值都是带分隔符的字符串;
将代码重写为(如果您的代码已包含单引号)
List<string> rolls
string sql =@"SELECT enrolment_status, roll_number FROM
dt_modular_enrolment WHERE id_student = ? AND
roll_number in " + "( " + String.Join(",",rolls) + " )";
否则,如果您的roll不包含单引号,请在sql语句之前添加以下几行:
for(int i=0;i<rolls.Count;i++)
{
rolls[i]="'"+ rolls[i]+ "'";
}
答案 3 :(得分:-1)
请使用以下代码检查您的代码... 由于您没有提到存储在卷中的内容,我已经重写了您的代码以实现目标结果
List<string> rolls = new List<string>();
rolls.Add("ROLL4");//HERE THERE CAN BE A ISSUE
rolls.Add("ROLL6");
rolls.Add("ROLL5");
rolls.Add("ROLL1");
rolls.Add("ROLL2");
rolls.Add("ROLL3");
StringBuilder sb = new StringBuilder();
foreach (var roll in rolls)
sb.Append("'" + roll + "',");
string rollList = sb.ToString().TrimEnd(',');
string sql =
@"SELECT enrolment_status, roll_number FROM dt_modular_enrolment WHERE id_student = ?
AND roll_number in " + "( " + rollList + " )";
在编写上面的代码后,我得到以下作为我的输出 sql = SELECT enrolment_status,roll_number FROM dt_modular_enrolment WHERE id_student =? AND roll_number in('ROLL4','ROLL6','ROLL5','ROLL1','ROLL2','ROLL3') &安培; rollList ='ROLL4','ROLL6','ROLL5','ROLL1','ROLL2','ROLL3'