5

我正在使用 Oracle 数据库。我可以做到这一点:

    import pandas as pd
    import pandas.io.sql as psql
    import cx_Oracle as odb
    conn = odb.connect(_user +'/'+ _pass +'@'+ _dbenv)

    sqlStr = "SELECT * FROM customers"
    df = psql.frame_query(sqlStr, conn)

但我不知道如何处理绑定变量,如下所示:

    sqlStr = """SELECT * FROM customers 
                WHERE id BETWEEN :v1 AND :v2
             """

我尝试了这些变化:

   params  = (1234, 5678)
   params2 = {"v1":1234, "v2":5678}

   df = psql.frame_query((sqlStr,params), conn)
   df = psql.frame_query((sqlStr,params2), conn)
   df = psql.frame_query(sqlStr,params, conn)
   df = psql.frame_query(sqlStr,params2, conn)

以下作品:

   curs = conn.cursor()
   curs.execute(sqlStr, params)
   df = pd.DataFrame(curs.fetchall())
   df.columns = [rec[0] for rec in curs.description]

但这个解决方案只是......不雅。如果可以的话,我想在不创建光标对象的情况下执行此操作。有没有办法只使用熊猫来完成整个事情?

4

2 回答 2

1

尝试使用pandas.io.sql.read_sql_query. 我使用了 pandas 0.20.1 版,我使用了它,它成功了:

import pandas as pd
import pandas.io.sql as psql
import cx_Oracle as odb
conn = odb.connect(_user +'/'+ _pass +'@'+ _dbenv)

sqlStr = """SELECT * FROM customers 
            WHERE id BETWEEN :v1 AND :v2
"""
pars = {"v1":1234, "v2":5678}
df = psql.frame_query(sqlStr, conn, params=pars)
于 2017-06-30T03:17:29.147 回答
0

据我所知,pandas 期望 SQL 字符串在传递之前完全形成。考虑到这一点,我会(并且总是)使用字符串插值:

params = (1234, 5678)
sqlStr = """
SELECT * FROM customers 
WHERE id BETWEEN %d AND %d
""" % params
print(sqlStr)

这使

SELECT * FROM customers 
WHERE id BETWEEN 1234 AND 5678

所以这应该psql.frame_query很好。(根据我对 postgres、mysql 和 sql server 的经验,它确实如此)。

于 2013-02-15T01:58:03.157 回答