gpt4 book ai didi

python - 为什么我的 Python 元组只存储第一个值?

转载 作者:行者123 更新时间:2023-11-30 22:12:36 25 4
gpt4 key购买 nike

我在我的 python 脚本中存储一个带有元组的 mysql 查询。我在脚本中有一个 raw_input 变量,我想检查它们是否与元组匹配。

curs.execute("""SELECT username, id FROM employees WHERE gid!=4""")
rows=curs.fetchall()
db.close()

uname = raw_input('Type the username for the new device: ')

for row in rows:
user = row[0]
empid = row[1]

if user == uname:
print 'User ' + uname + ' found...'
else:
print 'Not Found'

这仅在我键入第一位员工的用户名时有效。任何其他员工返回“未找到”

我注意到如果我删除 raw_input 行和 if 语句并添加

for row in rows:
user = row[0]
empid = row[1]
print user

它打印所有的值

最佳答案

根据我假设您正在尝试做的事情,这可能是更好的方法。

当您可以简单地将其添加到您的 WHERE 子句时,Python 中的循环没有理由搜索用户。

# Get the username from input
uname = raw_input('Type the username for the new device: ')

# Check to see if username in table
curs.execute("SELECT username, id FROM employees WHERE gid != 4 AND LOWER(username) = %s", (uname.lower(),))
row = curs.fetchone() # If no records found, should return an empty tuple
db.close()

# Return the user if found
if row:
user = row[0]
empid = row[1]
print 'User ' + user + ' found...'
else
print 'Not Found'

这将返回用户名(如果找到)。否则为“未找到”。

关于python - 为什么我的 Python 元组只存储第一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39577443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com