我可以在一个变量中存储一个cursor.fetchone()

时间:2012-04-30 04:50:44

标签: python

地狱的家伙刚跳进python,我很难搞清楚这个

我有2个查询。 。 query1 query2 现在我该怎么说呢 row = cursor.fetchone() ,我指的是 query1 而不是 query2

cursor = conn.cursor()
query1  = cursor.execute("select * FROM spam")
query2  = cursor.execute("select * FROM eggs")
row = cursor.fetchone ()

谢谢你们

3 个答案:

答案 0 :(得分:3)

执行第二个查询后,第一个查询的结果就消失了。 (execute的返回值没有用。)同时处理两个查询的正确方法是使用两个游标:

cursor1 = conn.cursor()
cursor2 = conn.cursor()
cursor1.execute("select * FROM spam")
cursor2.execute("select * FROM eggs")
cursor1.fetchone() #first result from query 1
cursor2.fetchone() #first result from query 2

答案 1 :(得分:1)

没有。来自cursor.execute的返回值毫无意义。每PEP 249

.execute(operation[,parameters]) 

        Prepare and execute a database operation (query or
        command)...

        [...]

        Return values are not defined.

答案 2 :(得分:1)

你无法按照自己的方式去做。做这样的事情:

cursor = conn.cursor()
cursor.execute("select * FROM spam")
results1 = cursor.fetchall()
cursor.execute("select * FROM eggs")

if results1 is not None and len(results1) > 0:
    print "First row from query1: ", results1[0]

row = cursor.fetchone()
if row is not None:
    print "First row from query2: ", row