pymysql的callproc()似乎影响后续的select查询

3 投票
1 回答
4622 浏览
提问于 2025-04-17 06:47

我正在尝试把一个代码库从使用MySQLdb转换为pymysql。现在遇到了一些问题,想知道有没有人遇到过类似的情况。

简单来说,当我通过pymysql的游标调用callproc()方法来执行一个存储过程后,接下来用同一个或不同的游标通过execute()方法进行的'select'查询返回的结果都是不正确的。我在Python 2.7.2和Python 3.2.2上都看到了同样的问题。

难道callproc()方法在某种程度上锁住了服务器?下面是代码:

conn = pymysql.connect(host='localhost', user='me', passwd='pwd',db='mydb')

curr = conn.cursor()

rargs = curr.callproc("getInputVar", (args,))
resultSet = curr.fetchone()
print("Result set   : {0}".format(resultSet))

# curr.close()
#
# curr = conn.cursor()

curr.execute('select * from my_table')
resultSet = curr.fetchall()
print("Result set len : {0}".format(len(resultSet)))        

curr.close()
conn.close()

我可以取消注释上面的close()和游标创建的调用,但这并没有改变结果。如果我注释掉callproc()的调用,select语句就能正常工作。

1 个回答

0

我遇到了一个类似的问题,就是提交的INSERT语句在数据库中没有显示出来。我使用的是PyMySQL 0.5,Python 3.2和MySQL Community Server 5.5.19。

我找到了解决办法:我没有使用execute()方法,而是用了executemany方法,具体可以在这个模块参考中找到解释:http://code.google.com/p/pymssql/wiki/PymssqlModuleReference,里面还有一些示例链接。

更新 稍后我发现,这还不是完整的解决方案。因为在Python脚本结束时,如果exit()执行得太快,数据会在数据库中丢失。 所以,我在关闭连接和exit()之前加了一个time.sleep(),结果所有数据都显示出来了! (我还改用了myisam表)

import pymysql
conn = pymysql.connect(host='localhost', user='root', passwd='', db='mydb', charset='utf8')
conn.autocommit(True)
cur = conn.cursor()

# CREATE tables (SQL statements generated by MySQL workbench, and exported with Menu -> Database -> Forward Engineer)
cur.execute("""
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';

DROP SCHEMA IF EXISTS `mydb` ;
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `mydb` ;
# […]

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

""")

# Fill lookup tables:

cur.executemany("insert into mydb.number(tagname,name,shortform) values (%s, %s, %s)", [('ЕД','singular','sg'), ('МН','plural','p')] )
cur.executemany("insert into mydb.person(tagname,name,shortform) values (%s, %s, %s)", [('1-Л','first','1st'), ('2-Л','second','2nd'), ('3-Л','third','3rd')] )
cur.executemany("insert into mydb.pos(tagname,name,shortform) values (%s, %s, %s)", [('S','noun','s'), ('A','adjective','a'), ('ADV','adverb','adv'), ('NUM','numeral','num'), ('PR','preposition','pr'), ('COM','composite','com'), ('CONJ','conjunction','conj'), ('PART','particle','part'), ('P','word-clause','p'), ('INTJ','interjection','intj'), ('NID','foreign-named-entity','nid'), ('V','verb','v')] )
#[…]

import time
time.sleep(3)
cur.close()
conn.close()
time.sleep(3)
exit()

我建议去这个论坛/群组 https://groups.google.com/forum/#!forum/pymysql-users,可以和开发者进一步讨论。

撰写回答