使用pyMySQL连接数据库时遇到的几个问题

最近几天在折腾MySQL,遇到几个问题,整理一下,环境为python3.4,没有mysqldb,只好用pymysql。

1、使用with pymysql.connect() 语句时,返回的对象是cursor类型,不是connection类型,需要注意一下。

2、想要实现向数据库中添加记录时记录已存在则更新记录的功能,一开始考虑用on duplicate key update语句,但这样产生了一个新的问题,就是这样会导致自增长的主键不连续。产生的原因是因为表锁的机制问题。因为在执行该语句前无法确定是否需要插入新行。这种情况下MySQL默认的做法是先申请一个位置,若是执行insert操作的话就不会有问题,若执行update操作则这个位置就空下了,由此导致自增字段不连续。

有一种解决方法是设置innodb_autoinc_lock_mode=0,但这样可能会在并发插入时出现问题,虽然我的小数据库只有自己在用,为了学习起见还是换个方法……更详细的解释看这里

3、为了让自增长字段连续,最好采用simple insert的方式插入,因此需要用到存储过程来对记录是否存在做判定。

with pymysql.connect(**self.login) as cursor:
        info = self.recentMatch()
        for i in info:
                arg = (ins[0], ins[1], ins[2])
                cursor.callproc('updaterecentmatch', arg)

但是执行上述代码时,会报错

2014 Commands out of sync

网上查了下原因:
首先,参见1,cursor是cursor类型而非connection类型。
其次,在调用存储过程之后需要执行mysql_store_result()来从服务端取回结果,在python中是在创建cursor时执行该操作,调用完一次存储过程以后未清理,因此会报错。
由此在循环尾部添加cursor.nextset()或者放弃with,手动创建connection,然后将cursor放到for循环里面。
try:
    conn = pymysql.connect(**self.login)
    info = self.recentMatch()
    for i in info:
        cursor = conn.cursor()
        ins = list(i)
        arg = (ins[0], ins[1], ins[2])
        cursor.callproc('updaterecentmatch', arg)
        cursor.close()
except Exception as e:
    print(e)
finally:
    conn.close()
# with pymysql.connect(**self.login) as cursor:
#     info = self.recentMatch()
#     for i in info:
#         ins = list(i)
#         arg = (ins[0], ins[1], ins[2])
#         cursor.callproc('updaterecentmatch', arg)
#         while cursor.nextset() is not None:
#             pass

参考:
MySQL-python: Commands out of sync
stackoverflow:Python, “commands out of sync; you can't run this command now”
stackoverflow:Ways to avoid MySQLdb's “Commands out of sync; you can't run this command now” (2014) exception

你可能感兴趣的:(Python)