2016-09-19 81 views
1

我在我的python腳本中存儲了一個元組的mysql查詢w /。我在腳本中有一個raw_input變量,我想檢查它們是否與元組匹配。爲什麼我的Python Tuple只存儲第一個值?

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 

它打印出的所有值

+0

你的'if-else'塊之後是否有'return'或'break'?另外,你確定你的查詢正在返回多個記錄嗎? – Nicarus

+0

@idjaw - 'curs.fetchall()'返回元組列表。 – Nicarus

+0

@Nicarus doh..right! – idjaw

回答

0

這可能是一個更好的方法基於我假設你正在嘗試做的事情。

當你可以簡單地將它添加到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' 

這將返回用戶名,如果找到。否則'未找到'。

+0

這看起來不錯,我會在我回來的時候測試一下,如果它有效,將它標記爲答案。非常感謝您的幫助! – craisondigital

+0

這個作品非常棒! @尼卡魯斯感謝你幫助我,並提供給我新的代碼 – craisondigital

+0

@craisondigital - 樂於幫助。 – Nicarus

相關問題