使用pythonmysql、tornado fram检索列值

2024-06-28 14:55:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个web应用程序,使用tornado框架和mysql python作为数据库连接器。在

需求是这样的-当用户登录并说购买了一个产品时,数据库有一个具有userid的表,以及所有与产品相关的列,这些列都应该更新。在

所以有一个usertable,productsbound表。假设有5个id为1、2、3、4、5的用户。 因此,当用户3购买产品时,productsbound表将更新为用户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。在

因此,无论谁登录-他们的用户名都会正确显示,但是他们的userid被认为是1,并且productsbound表正在为firstuser更新。在

在mysql中我查询

^{pr2}$

它正确地显示了3。在

所以一切看起来都很好,但是有点不对劲!! 这让我发疯了。请帮帮我!!在


Tags: 用户id数据库应用程序dbuid产品mysql
2条回答

你试过用引号把%s括起来吗?另外,self.currentuser周围是否可能有一些空白?在

我会尝试:

uid = cur.execute("""SELECT userid FROM user_table WHERE username='%s'""", (username,))

问题是您试图从.execute方法获取uid值。请参考the Python Database API Specification v2.0 (PEP 249) section describing the .execute method,其中写着:

Return values are not defined.

换句话说,不要使用此方法的返回值——至少,除非您对模块非常熟悉,能够准确地理解它是如何实现的。在

相反,您需要使用另一个方法从游标“获取”结果集。The example section in the MySQL-Python User's Guide显示了使用这些方法之一.fetchone来获取单行:

To perform a query, you first need a cursor, and then you can execute queries on it:

c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
          WHERE price < %s""", (max_price,))

...

And now, the results:

>>> 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方法的返回值,以便以后访问它们。在

因此,要将此应用于示例,请替换以下行:

^{pr2}$

更像这样:

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

使用哪种模式取决于查询、环境和个人喜好。在这两种情况下,如果在表中找不到用户名,您可能还需要处理获取空集的可能性。在

相关问题 更多 >