【发布时间】:2014-06-26 14:32:43
【问题描述】:
我有一个 C# 应用程序,其中我遇到了这个问题:当我运行这个 sn-p 时:
第一道
public void GetList(List<string> liste, List<int> outliste)
{
foreach( string s in liste){
outliste.Add(SqlFunction(s));
}
}
public int SqlFunction(string str)
{
string query = "select id from user where name="+str;
...................
// return the id
}
执行时间为 51 秒
第二种方式
public void SqlSecondWayFunction(List<string> liste, List<int> outliste)
{
string query ="select id from user where (";
foreach(string str in liste){
query += "name=" str + "or ";
}
query += " 1=0 )";
...................
// fill outliste by the result of the query
}
执行时间是1m:19sec!!!!!!!!! (liste 的计数约为 11000)。
所以我需要知道为什么第一种方法更快?
【问题讨论】:
-
你知道他们都对 SQL 注入开放?
-
@user2711965 谢谢我知道,这只是一个简单的示例
-
第二个示例连接所有 where 块并将它们与
OR链接。然后在最后,将1=1附加到同样与OR链接的where 语句。这意味着它返回所有行,因为1=1始终为真 -
我更想知道为什么差异如此之小。具有包含数千个运算符的条件的查询应该需要更长的时间才能运行......
-
我怀疑第二种方法的主要问题是使用
query +=构建您的查询,在每个循环中,这会在堆上创建一个新字符串,而不仅仅是添加到现有字符串。请改用 StringBuilder。话虽如此,将列表作为参数传递有更好、更安全的方法。您使用的是什么 DBMS?
标签: c# sql .net collections ado.net