Featured image of post Python使用mysql问题汇总

Python使用mysql问题汇总

前言

记录下工作中的问题及解决方法

正文

  1. python中mysql查询返回字典
  2. 查询mysql数据,表中有数据,select条件无异常就是查不出数据。
  3. 生成流水序号
  4. 字符编码“UnicodeDecodeError: ‘utf8’ codec can’t decode byte 0xce in position 149: invalid continuation byte”

问题一:

在连接数据库时设置cursorclass类如下:

self.conn = MySQLdb.connect(host=gl.DBSEVER['IP'], port=gl.DBSEVER['PORT'],
user=gl.DBSEVER['USER'], passwd=gl.DBSEVER['PASSWORD'],
db=gl.DBSEVER['DBNAME'],
charset="utf8",
cursorclass=MySQLdb.cursors.DictCursor
)

问题二:

在5.1.73版本和5.6.26版本的mysql中查询语句没有问题;但在5.7.19版本的mysql中一直查不到。使用数据库工具执行命令可查。 最终确实是事务问题 在执行select语句后提交事务。

sql = "select * from test";
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()

问题三:

网上好多使用mysql存储过程实现,我自己就使用python代码试了下。10个线程同时取流水号没有重复。效率没测试。

def getSeqno(self):
    '''取流水号'''
    try:
		cur = self.conn.cursor()
        cur.execute("update seqlist set id = id + 1 where NAME='SEQNO'")
        cur.execute('select id from seqlist')
        self.conn.commit()
        row = cur.fetchone()
        cur.close()
    except Exception, e:
        gl.logmain.error(e)
        raise
    seq = row['id']
    return seq

问题四:

python字符编码与mysql字符编码不符合。

  1. 数据库设置成utf8编码

     vi/etc/my.cnf  
     在里面加入,已经有[XXX]的,在里面直接加入即可。   
     [mysqld]  
     character-set-server=utf8   
     [client]  
     default-character-set=utf8   
     [mysql]  
     default-character-set=utf8   
    
  2. python接连数据库设置utf8编码

     self.conn = MySQLdb.connect(host=gl.DBSEVER['IP'], port=gl.DBSEVER['PORT'],
     user=gl.DBSEVER['USER'], passwd=gl.DBSEVER['PASSWORD'],
     db=gl.DBSEVER['DBNAME'],
     charset="utf8",
     cursorclass=MySQLdb.cursors.DictCursor)
    
  3. 将数据语句转成utf8编码格式

     import sys
     reload(sys)
     sys.setdefaultencoding('utf-8')
    
     sql = "UPDATE tset set a=%s", "你好“)
     sql = sql.encode('utf-8')
    

其它记录:

mysql插入字典

row = dict(row)
columns = ', '.join(row.keys())
placeholders = ', '.join(['%s'] * len(row))
sql = "INSERT into test ( %s ) VALUES ( %s )" % (columns, placeholders)
sql = sql.encode('utf-8')

mysql更新字典

row = dict(row)
columns = '=%s, '.join(row.keys())
columns = columns + '=%s'
sql = "UPDATE test set %s where idx='%s' " % (columns, "100")
sql = sql.encode('utf-8')
cur = self.conn.cursor()
cur.execute(sql, row.values())

总结

工作中问题还是很多,这只是一小部分。记录下以备用

Licensed under CC BY-NC-SA 4.0
最后更新于 2024-05-06 22:34 CST
赣ICP备18015110号-1   
使用 Hugo 构建
主题 StackJimmy 设计