2

Possible Duplicate:
Python challenging string encoding

I am trying to put a list of tickers into a SQL query. I am new to Python.

cus is a list set up as ['x', 'y', ..., 'a']

test = psql.frame_query(
    "select * from dataBase where cus IN (%r)", con = db) % cus

I tried this and it failed.

My next attempt was to try and remove the brackets and then paste the list in. How do I remove the brackets so that I get:

cus2 = 'x', 'y', ..., 'a'

I was going to do:

str = "select * from dataBase where cus IN (%r)" % cus2
test2 = psql.frame_query(str, con = db)

Or is there another way I should be attempting this?

Thank you.

4

1 回答 1

3

使用 SQL,您确实希望避免将值插入到查询中。您通常将其留给数据库适配器,该适配器具有有关如何避免从您的值创建危险 SQL 的专业知识(SQL 引用转义,也称为 SQL 注入攻击)。

不幸的是,该pandas.io.sql模块只是半心半意地实现了参数支持。

而不是使用frame_query,直接使用DataFrame.from_records()

首先,生成带参数的 SQL 查询。SQL 参数的格式因数据库适配器而异,因为Python DB API 标准允许一些变体。我假设您在这里使用 MySQL,它%s用于位置参数,与 Python 的语法相呼应:

sql = "select * from dataBase where cus IN ({0})".format(', '.join(['%s'] * len(cus2)))

这为 中的每个值创建了足够的参数cus2。然后查询数据库:

cur = psql.execute(sql, con, params=cus2)
rows = cur.fetchall()
columns = [col_desc[0] for col_desc in cur.description]
cur.close()

result = DataFrame.from_records(rows, columns=columns, coerce_float=True)

由于您似乎正在使用Sybase模块模块进行连接,因此您必须针对库使用的(有些非标准的)SQL 参数语法进行调整。它只接受命名参数,使用形式@name

params = dict(('@param{0}'.format(i), v) for i, v in enumerate(cus2))
sql = "select * from dataBase where cus IN ({0})".format(
    ', '.join(sorted(params.keys())))

cur = psql.execute(sql, con, params=params)
rows = cur.fetchall()
columns = [col_desc[0] for col_desc in cur.description]
cur.close()

result = DataFrame.from_records(rows, columns=columns, coerce_float=True)
于 2012-12-18T16:38:37.783 回答