C# 将图像存储到 MySQL 数据库
在 C# 中,可以使用以下代码将图像以二进制数据存储到 MySQL 表格中:
using MySql.Data.MySqlClient;
using System.IO;
// 读取图像文件并转换为字节数组
byte[] imageBytes = File.ReadAllBytes('path_to_image.jpg');
// 建立数据库连接
string connectionString = "server=your_server;user=your_username;database=your_database;password=your_password;";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
// 打开数据库连接
connection.Open();
// 创建 SQL 语句
string sql = "INSERT INTO images (image_data) VALUES (@imageData)";
// 创建命令对象并设置参数
using (MySqlCommand command = new MySqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@imageData", imageBytes);
// 执行命令
command.ExecuteNonQuery();
}
// 关闭数据库连接
connection.Close();
}
上述代码假设已经通过 NuGet 安装了 MySQL 数据库的驱动程序。请确保将以下值替换为您自己的数据库连接信息:
your_server:MySQL 服务器地址your_username:MySQL 用户名your_database:要使用的数据库名称your_password:MySQL 密码path_to_image.jpg:要存储的图像文件路径
此代码将图像文件读取为字节数组,并将其作为参数插入到名为 images 的表格的 image_data 列中。您需要根据自己的数据库结构和要插入的表格和列名进行调整。
原文地址: https://www.cveoy.top/t/topic/xkf 著作权归作者所有。请勿转载和采集!