我正在开发一个Web应用程序,使用tornado框架和mysql-python作为数据库连接器。
要求是这样的 - 当用户登录并说购买产品时,数据库有一个包含userid的表,以及所有与产品相关的列,应该更新。
所以有一个有用的,productbought表。假设有5个用户ID为1,2,3,4,5。 因此,当用户3购买产品时,productsbought表将使用用户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。
所以无论谁登录 - 他们的用户名都会正确显示,但他们的用户名被视为1,而且productbought表正在为第一位用户更新。
在我查询的mysql中
select userid from user_table where username = "thirduser"
它正确显示3。
所以一切看起来都不错,但有些不对劲!! 这让我疯了。请帮帮我!!
答案 0 :(得分:0)
您是否尝试将%s包装在引号中?此外,是否有可能在self.currentuser
周围有一些空白?
我试试:
uid = cur.execute("""SELECT userid FROM user_table WHERE username='%s'""", (username,))
答案 1 :(得分:0)
问题在于您尝试从uid
方法获取.execute
值。请参阅the Python Database API Specification v2.0 (PEP 249) section describing the .execute method,其中包含:
未定义返回值。
换句话说,不要使用此方法的返回值 - 至少,除非您对模块足够熟悉,否则无法理解 它正在实施。
相反,你需要使用另一种方法来"获取"光标的结果集。 The example section in the MySQL-Python User's Guide显示了使用其中一种方法.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元组的元组)。这意味着您应该存储fetch方法的返回值,以便以后访问它们。
因此,要将此应用于您的示例,请替换此行:
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
您使用的模式取决于查询,环境和您的个人品味。在任何一种情况下,如果在表中找不到用户名,您可能还想处理获取空集的可能性。