0
点赞
收藏
分享

微信扫一扫

pymysql使用变化的变量,构造SQL语句

北邮郭大宝 2022-02-27 阅读 130

主要使用的是format()方法,构造字符串

format用法示例:

print("姓名:{},年龄:{}岁".format("小A", -1))

得到结果:姓名:小A,年龄:-1岁

同理,使用sql时,使用:

import pymysql

mysql_config = {
    "db": "test_db",
    "host": "127.0.0.1",
    "user": "user",
    "password": "password",
}
conn = pymysql.connect(**mysql_config)
cursor = conn.cursor()
sql = """
SELECT `name`,`age`  FROM {table}
WHERE `age` < '{age}';
""".format(table="user_table", age=12)
cursor.execute(sql)
all_result = cursor.fetchall()  # 得到所有结果
cursor.close()
conn.close()

此时的sql就是:

SELECT `name`,`age`  FROM user_table
WHERE `age` < 12;
举报

相关推荐

0 条评论