[英]How to get a result from multiple select statements with pymysql
基本上,我有以下示例(假設cur來自有效連接):
>>> con = pymysql.connect(<parameters go here>)
>>> cur = con.cursor()
>>> sql = "SELECT @a := 0; SELECT @a := @a+2; SELECT @a;"
>>> res = cur.execute(sql)
>>> res
1
如您所見, res
返回整數1,這表示sql
良好。 但是,最后一次選擇應該返回數字2,而我需要該數字。
如果運行此代碼(由@falsetru建議),我也不會得到所需的東西:
>>> cur.execute(sql)
1
>>> cur.fetchall()
[{u'@a := 0': 0}]
我如何找回它? 是否可以不分離SQL語句?
使用Cursor.fetchone
獲取單行,或使用Cursor.fetchmany
/ Cursor.fetchall
獲取很多或所有結果行。
row = cur.fetchone()
a = row[0]
UPDATE Cursor.execute
執行單個sql語句,因此分別執行語句(通過將sql
分隔為;
)
import pymysql
con = pymysql.connect(user='root', password='root')
cur = con.cursor()
sql = "SELECT @a := 0; SELECT @a := @a+2; SELECT @a;"
for stmt in sql.split(';'):
if stmt.strip():
cur.execute(stmt)
row = cur.fetchone()
a = row[0]
print(a) # => 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.