[英]Passing table name as a function parameter in Python/Pandas/PostgreSQL
I am trying to call table_name in my SQL query using the 'new' secure way (it is good against SQL injection attacks) as in here: http://initd.org/psycopg/docs/sql.html#module-psycopg2.sql but I can't make it work with my code (table_name is a parameter of my function). 我试图在我的SQL查询中使用'new'安全方式调用table_name(它可以很好地防止SQL注入攻击),如下所示: http : //initd.org/psycopg/docs/sql.html#module-psycopg2。 sql但我无法使用我的代码(table_name是我的函数的参数)。
import pandas as pd
import psycopg2 as pg
import pandas.io.sql as psql
from psycopg2 import sql
sql_query = sql.SQL("SELECT * FROM {} limit %d offset %d" % (table_name, chunk_size, offset)).format(sql.Identifier(table_name))
df = psql.read_sql_query(sql_query, connection)
Any suggestions? 有什么建议么?
UPDATE (after a suggested answer): 更新(在建议的答案之后):
I tried with 我试过了
def import_table(self, connection, table_name, chunk_size, offset):
sql = "SELECT * FROM {} limit %d offset %d"
qry = sql.format(**dict(table=table_name)) %(chunk_size, offset)
df_piece = psql.read_sql_query(qry, connection)
And then calling it with: 然后调用它:
df = pd.concat(import_table(pg.connect("dbname=my_db user=my_user"), 'table_name', 100000, 0))
But I am getting an error: 但我收到一个错误:
---> 30 qry = sql_ct.format(**dict(table=table_name)) % (chunk_size, offset)
31 df_piece = psql.read_sql_query(qry, connection)
32
IndexError: tuple index out of range
Table names/column names can't be parameterized this way. 表名/列名不能以这种方式参数化。
It can and should be applied to values. 它可以而且应该应用于价值观。
Please read about Prepared statement 请阅读准备好的声明
Consider the following technique: 考虑以下技术:
# param. for str format: vvvvv
In [9]: qry = "SELECT * FROM {table} limit %d offset %d"
In [10]: qry.format(**dict(table='my_table')) %(10, 500)
Out[10]: 'SELECT * FROM my_table limit 10 offset 500'
UPDATE: 更新:
In [53]: my_table = 'table_name'
In [54]: qry
Out[54]: 'SELECT * FROM {table} limit %d offset %d'
In [55]: qry.format(**dict(table=my_table)) %(10, 500)
Out[55]: 'SELECT * FROM table_name limit 10 offset 500'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.