Python - 代码中的多个 SQL 查询

标签 python mysql sql python-2.7 while-loop

我正在创建一个接收输入(13 位数字)的 Python 脚本。然后获取该号码并检查它是否在我的数据库中(以检查该人是否已注册)。之后,它需要检查那个人是否登录(在我的数据库中,我有一个名为“status”的列,它是 0 或 1)。我这辈子都想不出如何在我的代码中执行第二个查询。

我正在使用 Python 2.7 和 MySQLdb 模块。

请参阅下面的代码:

导入MySQLdb

# Create a database connection
db = MySQLdb.connect(host="******", user="******", passwd="*****", db="******")
cur = db.cursor()

# Create a query to select all IDs
cur.execute("SELECT id, FROM users")
clientArray = []

# Loop over all IDs returned from query,
# save all IDs in the clientArray
for row in cur.fetchall():
    clientID = str(row[0])
    clientArray.append(clientID)
print clientArray #Printing for troubleshooting, ignore this


# Loop infinitely until - when you receive an input (which will be the clientID)
# check if the clientID exists in the clientArray.

# If the clientID exists, check to see whether the client has already been checked in
# If the client checkin returns FALSE, check the client in - turn on a GREEN LED light
# If the client checkin returns TRUE, check the client out - turn on a RED light

# If the clientID does not exist in clientArray, turn on the RED and GREEN LED lights

clientIDInput = ""
while True:
    clientIDInput = raw_input("")
    if clientIDInput in clientArray:
        print "The ID has been found in the database"
        # Check to see whether the person has been logged in or not

        ### THIS CODE DOES NOT WORK, CAN'T FIGURE THIS PART OUT ###
        cur.execute("SELECT status FROM users WHERE id='clientIDInput'")
        clientStatus = cur.fetchall()
        if clientStatus == True:
            print "This person is already checked in. Checking out now." 
            # Update MySQL database and change status from 1 to 0
        if clientStatus == False:
            print "This person has not checked in yet. Checking in now."
            # Update MySQL database and change status from 0 to 1        
    else:
        print " The ID has not been found in the database"

最佳答案

您需要参数化查询并将 clientIDInput 变量值传递给它。然后,使用fetchone()获取结果:

cur.execute("SELECT status FROM users WHERE id=%s", (clientIDInput, ))
data = cur.fetchone()
if not data:
    print "The ID has not been found in the database"
else:
    status = data[0]
    if status:
        print "This person is already checked in. Checking out now." 
        # Update MySQL database and change status from 1 to 0
    else:
        print "This person has not checked in yet. Checking in now."

希望我能正确理解用例和逻辑。

关于Python - 代码中的多个 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35040276/

相关文章:

java - 有没有办法检查文档中是否存在标签名称? (DOM - Jython)

mysql - 为什么mysql插入忽略增加自增字段?

mysql - 如何在Hibernate xml文件中映射Memory(HEAP) MySql表?

.net - 使用 Npgsql 提供程序 (.NET) 执行 sql 文件

python - Numpy 会自动检测和使用 GPU 吗?

python - Scrapy-Splash:无法使用 scrapinghub/splash:latest 作为基础镜像运行 docker 容器

mysql - SQL 删除与级联

php - 一个我没有得到的错误,MYSQL PDO PHP

sql - 在 Group By 查询中划分值

python - 为什么Python程序员不经常使用属性?