where 1=1始終為true,在構(gòu)造動態(tài)sql語句時,能夠保證查詢語句恒正確。
where 1=0; 這個條件始終為false,結(jié)果不會返回任何數(shù)據(jù),只有表結(jié)構(gòu),可用于快速建表。
動態(tài)sql語句的一些問題
string MySqlStr="select * from table where";
if(Age.Text.Lenght>0)
{
MySqlStr=MySqlStr+“Age="+"'Age.Text'";
}
if(Address.Text.Lenght>0)
{
MySqlStr=MySqlStr+"and Address="+"'Address.Text'";
}
如果兩個if語句均不成立,那么MySqlStr動態(tài)構(gòu)造語句就變成了:
MySqlStr="select * from table where"
這是一條錯誤的語句,不能被執(zhí)行,會報錯,這并不是一種好的編碼方式,不夠魯棒。
使用where 1=1語句后
string MySqlStr="select * from table where 1=1";
if(Age.Text.Lenght>0)
{
MySqlStr=MySqlStr+“and Age="+"'Age.Text'";
}
if(Address.Text.Lenght>0)
{
MySqlStr=MySqlStr+"and Address="+"'Address.Text'";
}
若兩個if不成立,MySqlStr語句就變成了:
MySqlStr="select from table where 1=1;
該語句語法正確,它的作用相當于:MySqlStr=”select * from table;,被執(zhí)行后,返回表中所有數(shù)據(jù)。意思就是,用戶在多條件查詢時,不輸入任何條件,就會返回表中所有數(shù)據(jù)。
where 0=1語句
where 1=0; 這個條件始終為false,結(jié)果不會返回任何數(shù)據(jù),只有表結(jié)構(gòu),可用于快速建表
SELECT * FROM strName WHERE 1 = 0; 該select語句主要用于讀取表的結(jié)構(gòu)而不考慮表中的數(shù)據(jù),這樣節(jié)省了內(nèi)存,因為可以不用保存結(jié)果集。
create table newtable as select * from oldtable where 1=0; 創(chuàng)建一個新表,而新表的結(jié)構(gòu)與查詢的表的結(jié)構(gòu)是一樣的。