python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python操作MySQL数据类型转换

Python中操作MySQL数据库时如何处理数据类型转换问题

作者:Python 老手

日常工作中,我们难免会遇到要直连数据库来进行数据的读取与处理,然而会有几种比较有特点的数据需要进行转换,这篇文章主要介绍了Python中操作MySQL数据库时如何处理数据类型转换问题的相关资料,需要的朋友可以参考下

一、先搞懂:Python 与 MySQL 数据类型的默认映射

pymysql会自动完成基础类型的转换,你先记住核心映射规则,大部分场景不用手动处理:

MySQL 数据类型Python 类型说明
INT/TINYINT/BIGINTint整数类型直接映射
FLOAT/DOUBLE/DECIMALfloat/DecimalDECIMAL 默认转 float(需精准则手动转)
VARCHAR/TEXTstr字符串自动转 Unicode
DATE/DATETIME/TIMESTAMPdatetime.datetime日期时间自动转 datetime 对象
BOOLEANboolMySQL 的 BOOL 本质是 TINYINT (1)
NULLNone空值对应 Python 的 None
BLOBbytes二进制数据转 bytes

二、手动处理数据类型转换的场景与示例

自动转换满足 80% 的场景,但遇到精度要求高格式自定义特殊类型时,需要手动干预,以下是高频场景:

1. 场景 1:DECIMAL 类型(金额 / 精度数据)避免浮点误差

MySQL 的 DECIMAL 用于存储金额、汇率等精准数值,pymysql默认转 float 会丢失精度,需手动转decimal.Decimal

import pymysql
from decimal import Decimal

# 1. 连接时指定转换规则(推荐)
config = {
    'host': 'localhost',
    'user': 'root',
    'password': '你的密码',
    'database': 'test_db',
    'conv': pymysql.converters.conversions.copy()  # 复制默认转换规则
}
# 重写DECIMAL转换规则:转Decimal而非float
config['conv'][pymysql.FIELD_TYPE.DECIMAL] = Decimal
config['conv'][pymysql.FIELD_TYPE.NEWDECIMAL] = Decimal

# 2. 连接并查询
connection = pymysql.connect(**config)
cursor = connection.cursor(pymysql.cursors.DictCursor)

# 创建测试表(含DECIMAL字段)
cursor.execute("""
CREATE TABLE IF NOT EXISTS order_info (
    id INT AUTO_INCREMENT PRIMARY KEY,
    order_no VARCHAR(20),
    amount DECIMAL(10,2)  # 金额,10位总长度,2位小数
)
""")
# 插入数据(直接传Decimal更精准)
cursor.execute("INSERT INTO order_info (order_no, amount) VALUES (%s, %s)", 
               ("ORD202501", Decimal("99.99")))
connection.commit()

# 查询验证(amount直接是Decimal类型)
cursor.execute("SELECT * FROM order_info WHERE id = %s", (1,))
result = cursor.fetchone()
print(f"金额:{result['amount']},类型:{type(result['amount'])}")  # 输出:99.99,类型:<class 'decimal.Decimal'>

cursor.close()
connection.close()

2. 场景 2:日期时间类型的自定义格式转换

MySQL 的 DATETIME 自动转datetime.datetime,但有时需要转字符串(如接口返回)或自定义格式:

import pymysql
from datetime import datetime

connection = pymysql.connect(
    host='localhost',
    user='root',
    password='你的密码',
    database='test_db',
    cursorclass=pymysql.cursors.DictCursor
)
cursor = connection.cursor()

# 1. 写入:Python datetime对象直接传入(自动转MySQL DATETIME)
insert_time = datetime(2025, 1, 19, 10, 30, 0)
cursor.execute("INSERT INTO users (name, create_time) VALUES (%s, %s)", 
               ("王五", insert_time))
connection.commit()

# 2. 读取:datetime对象转自定义格式字符串
cursor.execute("SELECT create_time FROM users WHERE name = %s", ("王五",))
result = cursor.fetchone()
dt_obj = result['create_time']
# 转成"YYYY-MM-DD HH:MM:SS"字符串
dt_str = dt_obj.strftime("%Y-%m-%d %H:%M:%S")
print(f"创建时间:{dt_str},类型:{type(dt_str)}")  # 输出:2025-01-19 10:30:00,类型:str

# 3. 反向:字符串转datetime写入
dt_str2 = "2025-01-20 15:00:00"
dt_obj2 = datetime.strptime(dt_str2, "%Y-%m-%d %H:%M:%S")
cursor.execute("UPDATE users SET create_time = %s WHERE name = %s", 
               (dt_obj2, "王五"))
connection.commit()

cursor.close()
connection.close()

3. 场景 3:JSON 类型的处理(MySQL 5.7 + 支持)

MySQL 的 JSON 类型需手动序列化 / 反序列化(pymysql不会自动转 Python 字典):

import pymysql
import json

connection = pymysql.connect(
    host='localhost',
    user='root',
    password='你的密码',
    database='test_db',
    cursorclass=pymysql.cursors.DictCursor
)
cursor = connection.cursor()

# 1. 创建含JSON字段的表
cursor.execute("""
CREATE TABLE IF NOT EXISTS user_profile (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT,
    profile JSON  # JSON类型字段
)
""")

# 2. 写入:Python字典转JSON字符串
profile_dict = {"hobby": ["篮球", "编程"], "address": {"city": "北京"}}
profile_json = json.dumps(profile_dict, ensure_ascii=False)  # ensure_ascii=False保留中文
cursor.execute("INSERT INTO user_profile (user_id, profile) VALUES (%s, %s)", 
               (1, profile_json))
connection.commit()

# 3. 读取:JSON字符串转Python字典
cursor.execute("SELECT profile FROM user_profile WHERE user_id = %s", (1,))
result = cursor.fetchone()
profile_str = result['profile']
profile_dict2 = json.loads(profile_str)
print(f"爱好:{profile_dict2['hobby']},城市:{profile_dict2['address']['city']}")
# 输出:爱好:['篮球', '编程'],城市:北京

cursor.close()
connection.close()

4. 场景 4:BLOB / 二进制数据(如图片、文件)

MySQL 的 BLOB 类型对应 Python 的 bytes,读写时需处理二进制数据:

import pymysql

connection = pymysql.connect(
    host='localhost',
    user='root',
    password='你的密码',
    database='test_db',
    cursorclass=pymysql.cursors.DictCursor
)
cursor = connection.cursor()

# 1. 创建含BLOB字段的表
cursor.execute("""
CREATE TABLE IF NOT EXISTS file_store (
    id INT AUTO_INCREMENT PRIMARY KEY,
    file_name VARCHAR(100),
    file_data BLOB  # 二进制数据字段
)
""")

# 2. 写入:读取文件转bytes写入
with open("test.jpg", "rb") as f:
    file_bytes = f.read()
cursor.execute("INSERT INTO file_store (file_name, file_data) VALUES (%s, %s)", 
               ("test.jpg", file_bytes))
connection.commit()

# 3. 读取:bytes写入文件
cursor.execute("SELECT file_data FROM file_store WHERE file_name = %s", ("test.jpg",))
result = cursor.fetchone()
file_bytes2 = result['file_data']
with open("test_copy.jpg", "wb") as f:
    f.write(file_bytes2)
print("文件已保存为test_copy.jpg")

cursor.close()
connection.close()

三、避坑要点

总结

到此这篇关于Python中操作MySQL数据库时如何处理数据类型转换问题的文章就介绍到这了,更多相关Python操作MySQL数据类型转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文