gpt4 book ai didi

python - Python中如何检查和执行SQL语句

转载 作者:行者123 更新时间:2023-11-30 23:34:22 24 4
gpt4 key购买 nike

我在 Python 中使用 MySQLdb。我被告知要正确创建 SQL 语句并避免 SQL 注入(inject)攻击,我应该编写如下代码:

sql = "insert into table VALUES ( %s, %s, %s )"
args = var1, var2, var3
cursor.execute( sql, args )

或者:

cursor.execute( "insert into table VALUES ( %s, %s, %s )", var1, var2, var3 )

甚至这个(这可能是错误的):

header = ( 'id', 'first_name', 'last_name' )
values = ( '12', 'bob' , 'smith' )
cursor.execute( "insert into table ( %s ) values ( %s )", ( header + values ) )

当我用 PHP 编程时,我通常会将整个 SQL 语句存储为一个长字符串,然后执行该字符串。类似于(使用 PostgreSQL):

$id         = db_prep_string( pg_escape_string( $id         ) );
$first_name = db_prep_string( pg_escape_string( $first_name ) );
$last_name = db_prep_string( pg_escape_string( $last_name ) );

$query = "insert into table ( id, first_name, last_name ) values ( $id, $first_name, $last_name )"

$result = pg_query( $con, $query );
$retval = pg_fetch_array( $result );

db_prep_string 在哪里

function db_prep_string( $value ) {
if(
!isset( $value ) ||
(is_null($value)) ||
preg_match( '/^\s+$/', $value ) ||
( $value == '' )
) {
$value = 'null';
}
else {
$value = "'$value'";
}
return $value;
}

然后为了调试,我可以简单地回显 $query 来查看整个 SQL 语句。我可以用 Python 做一些类似的事情吗?换句话说,我可以将安全 SQL 语句存储为一个字符串,打印出来进行调试,然后执行吗?

我想做这样的事情:

id         = prevent_sql_injection_string( id         )
first_name = prevent_sql_injection_string( first_name )
last_name = prevent_sql_injection_string( last_name )

sql = "insert into table ( id, first_name, last_name ) values "
sql += id + ", "
sql += first_name + ", "
sql += last_name

print sql #for debugging

cursor.execute( sql )

如果没有,那么如何在 Python 中查看完整的 SQL 语句?

奖励问题:如何使用 Python 在 SQL 语句中输入空值?

最佳答案

看看 Python Database API specification因为它回答了你的一些问题。例如,对于 NULL 值,API 规范是这样说的:

SQL NULL values are represented by the Python None singleton on input and output.

关于参数样式,规范为实现者提供了多种选择,包括 MySQLdb 使用的 'format' 选项。

如果您想查看 MySQLdb 将对您的数据库执行什么查询,您可以稍微作弊并使用连接 literal(...) 方法。例如:

>>> import MySQLdb
>>> db = MySQLdb.connect(...)
>>> print "insert into table VALUES ( %s, %s, %s )" % db.literal((5, "ab'c", None))
insert into table VALUES ( 5, 'ab\\'c', NULL )

但是 db.literal(...) 方法并不是真的要被 MySQLdb 模块的客户端使用,所以不要把它放在生产代码中。

另外,请注意 MySQLdb documentation关于参数有这样的说法:

Parameter placeholders can only be used to insert column values. They can not be used for other parts of SQL, such as table names, statements, etc.

因此请注意在插入语句中使用参数占位符作为表的列名。

关于python - Python中如何检查和执行SQL语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8874206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com