简体   繁体   English

带有占位符的熊猫read_sql。 “在哪里引起”错误

[英]Pandas read_sql with placeholders. 'Where cause' an error

Here is MS Access database , it contains a table. 这是MS Access 数据库 ,其中包含一个表。 I'd like to read it into DataFrame. 我想将其读入DataFrame。 The issue here is when "WHERE" is used it causes pyodbc.Error: ('07002', '[07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1. (-3010) (SQLExecDirectW) 这里的问题是当使用“ WHERE”时会导致pyodbc.Error :(“ 07002”,“ [07002] [Microsoft] [ODBC Microsoft Access驱动程序]参数太少。预期为1。(-3010)(SQLExecDirectW)

import pyodbc #conda install -c anaconda pyodbc
import pandas as pd
import os
db_path=os.path.realpath("test01.accdb")
conn_str = (
    r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};"
    f"DBQ={db_path};"
    )

#sql_str='''SELECT Table1.* FROM Table1''' # << this one works    
sql_str='''SELECT Table1.* FROM Table1 WHERE (((Table1.Column01)="DDD"))''' # << this one doesn't work

with pyodbc.connect(conn_str) as conn:    
    df=pd.read_sql(sql_str, conn)
print(df.head())

Database: 数据库:
Column01 Column02 列01列02
AAA BBB AAA BBB
CCC DDD CCC DDD
УУУ ГГГ УУУГГГ

Ah solved it. 嗯解决了。 This is my solution: 这是我的解决方案:

import pyodbc #conda install -c anaconda pyodbc
import pandas as pd
import os
db_path=os.path.realpath("test01.accdb")
conn_str = (
    r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};"
    f"DBQ={db_path};"
    )
sql_str='''SELECT Table1.* FROM Table1 WHERE Table1.Column01=?'''

with pyodbc.connect(conn_str) as conn:    
    df=pd.read_sql(sql_str, conn, params=("CCC",))
print(df.head())

To answer your original question, try it without the parentheses: 要回答您的原始问题,请尝试不使用括号:

sql_str = '''SELECT Table1.* FROM Table1 WHERE Table1.Column01 = "DDD"'''

However, if you're ever using a variable, it is best to use placeholders to validate your data against the column type in the WHERE clause and avoid possible SQL injection. 但是,如果您曾经使用过变量,则最好使用占位符来对照WHERE子句中的列类型验证数据,并避免可能的SQL注入。 Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM