[英]Retrieving column value, using python-mysql, tornado framework
我正在開發一個Web應用程序,使用龍卷風框架和mysql-python作為數據庫連接器。
要求是這樣的-當用戶登錄並說要購買產品時,數據庫中有一個包含用戶ID的表以及所有與產品相關的列,應對其進行更新。
因此,有一個用戶可用的產品購買表。 假設有5位ID為1,2,3,4,5的用戶。 因此,當用戶3購買產品時,所購買的產品表將使用用戶ID 3和他購買的產品的所有詳細信息進行更新。
出現問題。
username = self.current_user
print username # prints correct username say thirduser with id 3
db = MySQLdb.connect(host='localhost', user='root', db= 'db')
uid = None
cur = db.cursor()
uid = cur.execute("""Select userid from user_table where username = %s """, (username,))
print uid # should display 3, but displays 1
cur.execute("""INSERT INTO productsbought (userid, pid, pname, model) VALUES ( %s, %s, %s, %s)""", (uid, pid, pname, model,))
# The insert is working fine but for the wrong user.
現在,理想情況下,該uid應該顯示3(與登錄到應用程序的Thirduser對應的ID)。 但其印刷1。
因此,無論誰登錄-他們的用戶名都可以正確顯示,但他們的用戶ID被當作1,並且productfirst的產品購買表正在更新。
在MySQL中我查詢
select userid from user_table where username = "thirduser"
並且它正確顯示3。
所以一切看起來不錯,但是出了點問題!! 這讓我發瘋。 請幫幫我!!
您是否嘗試過將%s用引號引起來? 另外, self.currentuser
周圍self.currentuser
有空白?
我會嘗試:
uid = cur.execute("""SELECT userid FROM user_table WHERE username='%s'""", (username,))
問題是您正在嘗試從.execute
方法獲取uid
值。 請參閱Python數據庫API規范v2.0(PEP 249)部分,其中描述了.execute方法 ,其中指出:
未定義返回值。
換句話說, 請勿使用此方法的返回值 –至少,除非您對模塊足夠熟悉,以確切了解其實現方式,否則請不要使用。
相反,您需要使用另一種方法來從cursor中“獲取”結果集 。 《 MySQL-Python用戶指南》中的示例部分說明了如何使用以下一種方法.fetchone
來獲取單行:
要執行查詢,首先需要一個游標,然后可以對其執行查詢:
c=db.cursor() max_price=5 c.execute("""SELECT spam, eggs, sausage FROM breakfast WHERE price < %s""", (max_price,))
...
現在,結果:
>>> c.fetchone() (3L, 2L, 0L)
如果您期望只能從特定查詢中返回一行(例如,當匯總整個表時),那么使用.fetchone
是合理的。 如果有更多行,則可以重復調用此方法,直到用完所有行。 但是,在許多情況下,您需要使用.fetchall
來存儲整個集合:
>>> import MySQLdb
>>> conn = MySQLdb.connect(user='foo', passwd='bar', db='test')
>>> curs = conn.cursor()
>>> curs.execute('create temporary table t (a int);')
0L
>>> curs.executemany('insert into t values (%s);', xrange(10))
10L
>>> curs.execute('select count(*) from t;')
1L
>>> curs.fetchall()
((10L,),)
>>> curs.execute('select a from t where a % 2;')
5L
>>> curs.fetchall()
((1L,), (3L,), (5L,), (7L,), (9L,))
>>> curs.fetchall()
()
請注意,行僅被提取一次; 如果您第二次調用.fetchall
而不執行另一個查詢,則會得到一個空結果集(0元組的元組)。 這意味着您應該存儲獲取方法的返回值以便以后訪問它們。
因此,要將其應用於您的示例,請替換此行:
uid = cur.execute("""Select userid from user_table where username = %s """, (username,))
還有更多類似這樣的東西:
cur.execute("""Select userid from user_table where username = %s """, (username,))
result = cur.fetchone() # get a single row
uid = result[0] # get the first value from that row
或者,使用.fetchall
:
cur.execute("""Select userid from user_table where username = %s """, (username,))
result = cur.fetchall() # get any/all rows
uid = result[0][0] # get the first value from the first row
您使用哪種模式取決於查詢,環境和您的個人喜好。 無論哪種情況,如果在表中都沒有找到用戶名,您可能還希望處理獲取空集的可能性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.