SQL:where 1=1的各种作用
1.拷贝表结构create table table_name asselect * fromSource_table where1 <> 1;且select * from Source_table where 1=1;等同于 select * from Source_table;2.做SQL拼接时 为了满足语法规范SQL 语句中 where 条件后 写上1=1 是什么意思 - 晨起的太
1.拷贝表结构
create table table_name as select * from
Source_table where 1 <> 1;
且select * from Source_table where 1=1;等同于 select * from Source_table;
另有说法待验证(出自:Oracle海量数据查询优化_weixin_33894992的博客-CSDN博客)
select col1,col2 into #t from t where 1=0
这类代码不会返回任何结果集,但是会消耗系统资源的,应改成这样: create table #t(...)
2.做SQL拼接时 为了满足语法规范
我们在写代码的过程中,为了保证语法规范的时候,也会使用到where 1=1。
我们先看下面这段Java代码:
String sql="select * from table_name where 1=1"; if( condition 1) {
sql=sql+" and var2=value2";
} if(condition 2) {
sql=sql+" and var3=value3";
}
如果我们不写1=1的话,当condition 1为真时,代码拼接后被执行的SQL代码如下: select * from table_name where and var2=value2;
很明显,这里会出现一个SQL 的语法错误:and必须前后都有条件。
有人说我直接把where写在if语句里面,我就不写where 1=1。
String sql="select * from table_name"; if( condition 1) {
sql=sql+" where var2=value2 ";
} if(condition 2) {
sql=sql+" where var3=value3";
}
当condition 1为真,condition 2为假时,上面被执行的SQL代码为: select * from table_name where var2=value2;
这个确实没有语法错误,但是当condition 1和condition 2都为真呢?那么SQL语句就变成了这样: select * from table_name where var2=value2 where var3=value3;
很明显这是不符合SQL语法规范的。
这里写上where 1=1 是为了避免where 关键字后面的第一个词直接就是 “and”而导致语法错误,加上1=1后,不管后面有没有and条件都不会造成语法错误了。
3.缺点
select * from table where 1=1
但是因为table中根本就没有名称为1的字段,该SQL其实等效于select * from table,这个SQL语句很明显是全表扫描,需要大量的IO操作,数据量越大越慢。
所以在查询时,where1=1的后面需要增加其它条件,并且给这些条件建立适当的索引,效率就会大大提高。
4.关于1=1的SQL注入
4.1对 于 JDBC而言, SQL注入 攻 击 只 对 Statement有效, 对 PreparedStatement 是无效的, 这 是因 为 PreparedStatement 不允 许 在不同的插入 时间 改 变查询 的 逻辑结 构。
如 验证 用 户 是否存在的 SQL语 句 为 : select count(*) from usertable where name='用 户 名 ' and pswd='密 码 '
如果在 用 户 名字段 中 输 入 ' or '1'='1' or '1'='1
或是在 密 码 字段 中 输 入 1' or '1'='1
将 绕过验证 ,但 这种 手段只 对 只 对 Statement有效, 对 PreparedStatement 无效。
PreparedStatement 相 对 Statement有以下 优 点:
1.防注入攻击 2.多次运行速度快 3.防止数据库缓冲区溢出 4.代 码 的可读性可维护性好
4.2没有授予传参的权利情况下 where 1=1永远成立,而你担心的SQL注入问题是where后面紧跟传入的参数或语句,而这里并没有授予传参的权利而是直接写死1=1。
更多推荐
所有评论(0)