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)

 

posted @ 2019-01-31 14:53  一菲聪天  阅读(9698)  评论(0编辑  收藏  举报