我在Django 1.8中使用Postgres 9.4后端工作。我目前正在使用/* set up dummy datasets */
data have1;
retain test_1 test_2 test_3 0;
run;
data have2;
retain plu_1 plu_2 plu_3 0;
run;
data have3;
retain set_1 set_2 set_3 0;
run;
/* pull out column names and position from dictionary data */
proc sql;
create table temp as select name, varnum
from dictionary.columns
where upper(libname) = 'WORK' and upper(memname) in ('HAVE1','HAVE2','HAVE3');
quit;
/* sort by column position */
proc sort data=temp;
by varnum;
run;
/* put sorted column names into macro list */
proc sql noprint;
select name into :vars separated by ' '
from temp;
quit;
%put varlist = &vars.;
/* merge data with columns in correct position */
data want;
retain &vars.;
merge have1 have2 have3;
run;
运行以下查询:
django.db.connection
这有效,但它是否容易受到SQL注入攻击?
如果是这样,有什么方法可以在将cursor = connection.cursor()
codes = ['01', '02'] # these are actually obtained as GET parameters
query = "SELECT number_str, bnf_id, name FROM mytable WHERE "
for i, code in enumerate(codes):
q = "(number_str ILIKE '{}%' OR name ~* '{}') "
query += q.format(code, code)
if i < len(codes)-1:
query += 'OR '
cursor.execute(query)
传递给查询字符串之前将其codes
转义,这仍然适用于此正则表达式查询吗?
答案 0 :(得分:1)
我原以为 容易受到SQL注入攻击,因为您从用户那里获取了内容codes
,并且在将其放入查询之前不要检查或清除它
确保转义SQL命令的更好方法是使用execute
,如下所示:
query = "SELECT number_str, bnf_id, name FROM mytable WHERE "
for i, code in enumerate(codes):
q = "(number_str ILIKE %s OR name ~* %s) "
query += q
if i < len(codes)-1:
query += 'OR '
# create an interleaved list of '<code>%', '<code>' pairs:
qcodes1 = [s + '%' for s in codes]
qcodes2 = codes
qcodes = [code for p in zip(qcodes1, qcodes2) for code in p]
cursor.execute(query, qcodes)
(请注意逗号而不是%
中的execute
。
顺便说一下,Django对这种查询的查询集有什么问题?
答案 1 :(得分:-1)
您可以使用escape_string()
库中的MySQLDb
来引用字符串: