c# - 通过 C# 应用程序将图像保存在 MySQL 中

标签 c# mysql image-upload

我有一个 C# 客户端应用程序,用于获取图像(数据类型:VarChar) 的位置。然后,该应用程序应该调用一个 Web 服务,该服务又将图像(而不是位置)存储在本地 MySQL 数据库中。

问题是,我意识到我能够将除图像之外的所有其他数据从表单传递到数据库......任何人都可以指出我在这里做错了什么吗?任何帮助将不胜感激。

ps - 我知道你们很多人会建议我将图像保存在文件系统中而不是数据库本身......但问题是,我的数据库无论如何都没有那么大,所以保存图像希望数据库本身不会有什么大不了的:)

这是我在 MySQL 中的表,

create table testImage(
id int not null auto_increment,
name varchar(50),
age int,
image blob,
primary key(id));

这里是 WebMethod ,它的目的是将数据插入到表中...当 image 字段被注释掉时它会起作用。

[WebMethod]
        public string sendDataToMySql(string get_name, int get_age, byte[] buffer)
        {
            string MyConString = "SERVER=localhost;" +
                  "DATABASE=test;" +
                  "UID=root;" +
                  "PASSWORD=password;";

            string name_new = get_name;
            int age_new = get_age;
            byte[] buffer_new = buffer;


            MySqlConnection connection = new MySqlConnection(MyConString);
            connection.Open();
            MySqlCommand command = new MySqlCommand("", connection);
            command.CommandText = "insert into testdata(name, age, image) values(@name, @age, @image);";

            command.Parameters.AddWithValue("@name", name_new);
            command.Parameters.AddWithValue("@age", age_new);
            command.Parameters.AddWithValue("@image", buffer_new);

            command.ExecuteNonQuery();

            connection.Close();

            return "Task Performed!";

        }

最佳答案

我认为您根本不需要声明 buffer_new 变量,您只需按原样使用 buffer 参数即可。

我的猜测是,您应该将 MySql.Data.MySqlClient.MySqlDbType.Blob 数据类型分配给 @Image 参数,而不仅仅是 AddWithValue >...

在此处查看完整示例:Insert blob into MySQL

关于c# - 通过 C# 应用程序将图像保存在 MySQL 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8495482/

相关文章:

c# - 将 Base 64 字符串/图像上传到 Azure 存储图像时出现空白 c#

c# - "It was not possible to find any compatible framework version"与 ASP.NET Core 2.2

c# - 无法注册 Windows.Devices.Bluetooth

c# - 创建新类时如何传递类的实例?

c# - 一次上传多个 Ftp 文件

mysql - 查询事件持续时间

mysql - 在sql中转换日期

java - 持久化一个对象的成员,即一个实体 "has"而不是对象本身

c# - 亚马逊 S3.NET : Upload base64 image data?

php - 将带有缩略图的图像上传到文件夹并添加到 Mysql 的路径