1.工具环境
- Pycharm2018.3
- python3.7
- Anaconda3.7
- mysql5.7
- sqlalchemy1.2.15
2.问题描述
在插入数据的时候抛出以下异常:
Warning: (1366, "Incorrect string value: '\\xD6\\xD0\\xB9\\xFA\\xB1\\xEA...' for column 'VARIABLE_VALUE' at row 484")
result = self._query(query)
3.相关代码
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String(255))
sex = Column(String(8))
if __name__ == "__main__":
engine = create_engine("mysql+pymysql://root:password@localhost/my_db")
Session = sessionmaker(bind=engine)
user= User(name="测试", sex="男")
session = Session()
session.add(user)
session.commit()
session.close()
print("插入成功")
执行后抛出警告
驱动暂时使用的是pymysql,问题就在这里,各种网上搜索解决方案,基本上都是说字符集的不统一导致的,解决方法都是修改数据库和pycharm字符集,保持统一,但都没有效果,依然抛出异常
4.解决方法
1.安装mysql-connector-python驱动
conda install mysql-connector-python
2.修改代码
engine = create_engine("mysql+pymysql://root:password@localhost/my_db")
改为:
engine = create_engine("mysql+mysqlconnector://root:password@localhost/my_db")
执行后插入成功,一切正常