如何在 Python SQL 查询中使用变量? [英] How to use variables in Python SQL query?

查看:44
本文介绍了如何在 Python SQL 查询中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些复制粘贴的代码通过 Python/Flask 在 MySQL 数据库上执行 SQL 查询.我不熟悉它,它告诉我我尝试输入变量的方式不是正确的语法.

I'm using some copy-pasted code to do SQL queries on a MySQL DB through Python/Flask. I'm not familiar with it and it's telling me the way I'm trying to input a variable is not the correct syntax.

我的代码运行查询以查看电子邮件是否已存在.

My code runs a query to see if an email already exists.

问题代码:

def check_if_exists(val):
    import mysql.connector
    cnx = mysql.connector.connect(host=0.0.0.0", port=3306, user="username", passwd="password", db="testDB")
    cursor = cnx.cursor()
    query = """SELECT * FROM users WHERE email = val"""
    result = cursor.execute(query)
    print(result)

假设 val 是一列,但我希望它改用函数参数.

It's assuming val is a column, but I want it to use the function argument instead.

result = check_if_exists('random@email.com')
>>> True

推荐答案

您可以使用 %s 作为绑定值的占位符:

You can use %s as a placeholder for the bound value:

query = """SELECT * FROM users WHERE email = %s"""
result = cursor.execute(query, (val,))

这篇关于如何在 Python SQL 查询中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆