python mysql 编码问题

UnicodeEncodeError: ‘latin-1’ codec can’t encode character

在用python编写mysql操作时,当插入含有中文时会出现编码错误,这时候,需要指定编码方式为utf8编码

  • python2.x
#数据库操作
def Connection(host,user,passwd,database):
    db=MySQLdb.connect(host,user,passwd,database,charset='utf8')
    return db
  • python3.x
#数据库操作
def Connection(host,user,passwd,db):
    db=pymysql.connect(host,user,passwd,db ,use_unicode=True, charset='utf8')
    return db

注意:编码方式写为utf-8可能会出错,应写为utf8


python3.x完整代码

import pymysql

#数据库操作
def Connection(host,user,passwd,db):
    db=pymysql.connect(host,user,passwd,db ,use_unicode=True, charset='utf8')
    return db

def Add(db,item):
    cursor=db.cursor()
    #插入sql语句
    sql='insert into Swap(title,sdate,source,content)VALUES (%s,%s,%s,%s)'
    cursor.execute(sql,(item))
    #提交事务(这个一定要主动提交,不然在数据库中操作增、删结果不改变)
    db.commit()
    #关闭游标
    cursor.close()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章