Warning: (1366, "Incorrect string value: '\\xD6\\...' for column ...

Python solves SQLAlchemy+MySQL insert data time warning Warning: (1366, "Incorrect string value:'\xD6\…' for column…

1. Tool environment

Pycharm2018.3
python3.7
Anaconda3.7
mysql5.7
sqlalchemy1.2.15

2. Problem description

The following exception is thrown when inserting data:
Warning: (1366, “Incorrect string value:'\xD6\xD0\xB9\xFA\xB1\xEA…' for column'VARIABLE_VALUE' at row 484”)
result = self._query (query)

3. Related code

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("插入成功")

A warning is thrown after execution. The
image.png
driver temporarily uses pymysql. The problem is here. Various online search solutions are basically caused by the inconsistent character set. The solution is to modify the database and pycharm character set to maintain uniformity. , But no effect, still throws an exception

4. Solution

1. Install the mysql-connector-python driver
conda install mysql-connector-python
2. Modify the code

engine = create_engine("mysql+pymysql://root:password@localhost/my_db")

To:

engine = create_engine("mysql+mysqlconnector://root:password@localhost/my_db")

Inserted successfully after execution, everything is normal
image.png

Guess you like

Origin blog.csdn.net/xiaoxiaodechongzi/article/details/103241909