((MySQLdb._exceptions.ProgrammingError)参数不足,无法用于格式字符串

问题描述 投票:0回答:1

我正在使用以下查询从mysql数据库读取数据:设置:

conn = MySQLdb.connect(host='127.0.0.1', port=3306, user='**', passwd='**', db='***')
engine = create_engine('mysql+mysqldb://***')

sql = 'show tables like "{}"'.format('aTable_' + '%')

选项-1:可以。

a1 = pd.read_sql_query(sql, conn)

选项2:这将引发错误:ProgrammingError:(MySQLdb。exceptions.ProgrammingError)参数不足,无法用于格式字符串[SQL:显示类似“ aTable%”的表](此错误的背景位于:http://sqlalche.me/e/f405

a1 = pd.read_sql_query(sql, engine)

如果我想使用第二种样式(引擎作为参数),我该怎么办?

python pandas sqlalchemy mysql-python
1个回答
0
投票

不是使用字符串格式将值传递给SQL,而是使用占位符:

from sqlalchemy import text
engine = create_engine('mysql+mysqldb://***')
sql = text('SHOW TABLES LIKE :pattern')
a1 = pd.read_sql_query(sql, engine, params={'pattern': 'aTable_%'})
© www.soinside.com 2019 - 2024. All rights reserved.