【发布时间】: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