Python ORM SQLAlchemy 的中文乱码问题解决

本文介绍了如何处理Python ORM SQLAlchemy在操作数据库时遇到的中文乱码问题,提供了三种方法:1)通过URL字符串添加查询参数`?charset=utf8`;2)利用`connect_args`传递非字符串类型参数;3)自定义返回DBAPI连接的callable函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Custom DBAPI connect() arguments

Custom arguments used when issuing the connect() call to the underlyingDBAPI may be issued in three distinct ways. String-based arguments can bepassed directly from the URL string as query arguments:(第一种方式URL query string:加上"?charset=utf8")

db = create_engine('postgresql://scott:tiger@localhost/test?argument1=foo&argument2=bar')

If SQLAlchemy’s database connector is aware of a particular query argument, itmay convert its type from string to its proper type.

create_engine() also takes an argument connect_args which is an additional dictionary that will be passed to connect(). This can be used when arguments of a type other than string are required, and SQLAlchemy’s database connector has no type conversion logic present for that parameter:(第二种方式使用connect_arg参数方式)

db = create_engine('postgresql://scott:tiger@localhost/test', connect_args = {'argument1':17, 'argument2':'bar'})

The most customizable connection method of all is to pass a creatorargument, which specifies a callable that returns a DBAPI connection:

def connect():
    return psycopg.connect(user='scott', host='localhost')

db = create_engine('postgresql://', creator=connect)
在使用 SQLAlchemy 插入中文文本时,如果编码不正确,可能会导致乱码问题。为了防止这种情况发生,可以采用以下措施: 1. 确保数据库的编码与 Python 的编码一致,例如 UTF-8。 2. 在 SQLAlchemy 的 create_engine 函数中添加 charset 参数,指定编码方式。 3. 在插入数据时,将文本以 Unicode 格式传入。例如使用 u'中文' 的形式。 4. 对于批量插入,可以使用 SQLAlchemy 的 execute 函数和 executemany 函数,这些函数支持传入参数,可以在传入参数时指定编码方式。 以下是一个例子,使用 SQLAlchemy 批量插入中文文本: ```python from sqlalchemy import create_engine, Column, Integer, String, Text from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Message(Base): __tablename__ = 'message' id = Column(Integer, primary_key=True) content = Column(Text) engine = create_engine('mysql+pymysql://user:password@host:port/dbname?charset=utf8mb4') Session = sessionmaker(bind=engine) session = Session() data = [{'content': u'你好'}, {'content': u'世界'}] session.execute(Message.__table__.insert(), data) session.commit() ``` 在上述例子中,我们将数据库的编码设置为 UTF-8,使用了 pymysql 驱动程序,并将编码方式设置为 utf8mb4。同时,我们使用了 Unicode 编码的字符串 u'你好' 和 u'世界'。在批量插入时,我们使用了 execute 函数和 executemany 函数,将参数以列表的形式传递给函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值