这是MS Access database,它包含一个表。我想把它读入DataFrame。这里的问题是什么时候 使用“WHERE”会导致 pyodbc.Error:('07002','[07002] [Microsoft] [ODBC Microsoft Access Driver]参数太少。预期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())
数据库:
Column01 Column02
AAA BBB
CCC DDD
УУУГГГ
答案 0 :(得分:0)
啊解决了。这是我的解决方案:
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())
答案 1 :(得分:0)
要回答原始问题,请在没有括号的情况下尝试:
sql_str = '''SELECT Table1.* FROM Table1 WHERE Table1.Column01 = "DDD"'''
但是,如果您曾经使用过变量,最好使用占位符来根据WHERE
子句中的列类型验证数据,并避免可能的SQL注入。祝你好运!