【问题标题】:Python - Multiple SQL queries within codePython - 代码中的多个 SQL 查询
【发布时间】:2016-01-27 14:39:42
【问题描述】:

我正在创建一个接收输入(13 位数字)的 Python 脚本。然后获取该号码并检查它是否在我的数据库中(以检查此人是否已注册)。之后,它需要检查那个人是否登录(在我的数据库中,我有一个名为“状态”的列,它是 0 或 1)。在我的一生中,我无法弄清楚如何在我的代码中执行第二个查询。

我正在使用带有 MySQLdb 模块的 Python 2.7。

请参阅下面的代码:

导入 MySQL 数据库

# 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"

【问题讨论】:

    标签: python mysql sql python-2.7 while-loop


    【解决方案1】:

    您需要参数化查询并将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."
    

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

    【讨论】:

    • 太棒了!完美的解释。时间到了,我一定会把它标记为正确答案。不过有一个问题:cur.fetchone 检索的数据是:(1,0) 我如何确保它只检索 '1'?
    • @Cake fetchone() 返回一个元组,其中包含与您在查询中指定要选择的列一样多的项目。您实际执行的是什么查询?谢谢。
    • ` cur.execute("SELECT status FROM users WHERE id=%s", (clientIDInput, )) data = cur.fetchone()` 它应该只检索一个值,它确实如此。
    • 没关系,我用if data[0] == False解决了这个问题。感谢您花时间帮助我。我很感激。
    【解决方案2】:

    您不能直接将 'clientIDInput' 放入查询中。

    你需要这样做:

      cur.execute("SELECT status FROM users WHERE id='" + clientIDInput + "'")
    

    【讨论】:

    • 谢谢Ollie,这确实是问题所在。
    • 我不建议这样做 - 这会引发一系列新的安全问题,因为它容易受到 SQL 注入攻击
    • 我将使用您的解决方案@alecxe,但我确实要感谢 Ollie 指出您不能像我一样将变量放入查询中。 :)
    猜你喜欢
    • 2017-03-23
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 2014-05-12
    • 2021-11-18
    • 1970-01-01
    相关资源
    最近更新 更多