python navicat mysql 存入 class bytes 类型数据
时间: 2024-02-05 18:13:13 浏览: 28
在 Python 中,我们可以使用 MySQL Connector/Python 模块来连接 MySQL 数据库,使用该模块的 `Binary()` 函数将 bytes 类型数据存入 MySQL 数据库中的 BLOB 类型字段。
下面是一个示例代码:
```python
import mysql.connector
# 连接数据库
cnx = mysql.connector.connect(user='your_username', password='your_password',
host='your_host', database='your_database')
# 创建数据表
cursor = cnx.cursor()
table = """CREATE TABLE IF NOT EXISTS my_table (id INT AUTO_INCREMENT PRIMARY KEY, data BLOB)"""
cursor.execute(table)
# 定义要存入的 bytes 类型数据
my_data = b'Hello, World!'
# 将 bytes 类型数据存入 MySQL 数据库中的 BLOB 类型字段
sql = "INSERT INTO my_table (data) VALUES (%s)"
params = (mysql.connector.Binary(my_data),)
cursor.execute(sql, params)
cnx.commit()
# 关闭连接
cursor.close()
cnx.close()
```
在上面的示例代码中,我们首先连接 MySQL 数据库,并创建了一个名为 `my_table` 的数据表。然后定义了一个 bytes 类型的数据 `my_data`,并使用 `Binary()` 函数将其转换成 `mysql.connector.Binary` 类型,最后将其存入 `my_table` 表中的 `data` 字段中。