Adding image to blob (mysql) via c#

流过昼夜 提交于 2020-01-04 11:06:42

问题


I have made a C# application that adds images from the harddisk to a blob-field in mysql. I don't get errors and the blob-field is filled.

When I check the blob-field in MySQL Workbench it says the field is not correct (it can not show the image).

Whatever I do, whatever example I try, nothing seems to work. So it has no point to place any example code here, because nothing is working so far.

Does anyone have a good example code that I can try?

Thanks


回答1:


Okay, since some people wanted some code to be shown, I created a very simple console application with the help described in the link of Alex. I literally taken that code and placed in the console app. Some miracle happend, because it worked as soon as I started the app. I don't know what I did wrong in the main application, but it has to be something (duh). Here is the code:

string MyConString = "SERVER=localhost;" +
    "DATABASE=database;" +
    "UID=root;" +
    "PASSWORD=pass;";

System.IO.FileStream fs = new FileStream(@"D:\link\to\image.png", FileMode.Open);
System.IO.BufferedStream bf = new BufferedStream(fs);
byte[] buffer = new byte[bf.Length];
bf.Read(buffer, 0, buffer.Length);    

byte[] buffer_new = buffer;

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

command.Parameters.AddWithValue("@image", buffer_new);

command.ExecuteNonQuery();

connection.Close();

Console.WriteLine("Task Performed!");
Console.ReadLine();



回答2:


I find when working with mysql and .NET that the MySQL Connector makes things really easy!

This guy: Save Image in MySQL via C# application seems to be on the right lines.

Good Luck!




回答3:


Did you try to recover the blob via the mysql connector (the way you store it). MySQL Workbench doesn't displaying the image doesn't mean that isn't being stored.

Try to recover the image:

while (reader.read())
{
    var image = (byte[])reader.getColumn(0);
    File.WriteAllBytes(@"c:\image.extension", image);
}

This way you can ensure it's saving.



来源:https://stackoverflow.com/questions/12228967/adding-image-to-blob-mysql-via-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!