python 中 sql 带参数

使用 python 的字符串填充方式

import mysql.connector

sql = 'select \* from school.student where age > {age} and address = {addr};'
info = {'age' : 18, 'addr' : 'shenzhen'} # 参数是字典类型
sql = sql.format(\*\*info)

 mysql\_conn = mysql.connector.connect(host='host', user='user', passwd='password')
cursor = conn.cursor()
cursor.execute(sql)

使用 sql 模块中自带的填充方式

import mysql.connector

sql = 'select \* from school.student where age > %s and address = %s;' # 所有的填充字符都是 %s

 mysql\_conn = mysql.connector.connect(host='host', user='user', passwd='password')
cursor = conn.cursor()
info = (18, 'shenzhen') # 参数必须是 元组类型
cursor.execute(sql, info)