展开全部
这问题你之前问过,我估计是你用的mysql驱动的问题,今天有时32313133353236313431303231363533e58685e5aeb931333337623430间给你测试了一下,首先用的驱动是官方的mysql connector net 6.9.4,数据表里两列,一个id一个picture,后一个是longblobstatic string connstring = "Server=localhost;Uid=root;Password=12345;Database=demo";
private void button6_Click(object sender, EventArgs e)//插入数据并读取
{
FileStream fs = new FileStream(@"d:\Snap2.png", FileMode.Open, FileAccess.Read);
byte[] byImage = new byte[fs.Length];
fs.Read(byImage, 0, byImage.Length);
fs.Close();
string query = "update sortlist set picture=@fs where id=1";
if (InsertImg(connstring, query, byImage) > 0) MessageBox.Show("保存完成");
Image img = LoadImg(1);
if (img != null) pictureBox3.Image = img;
}
public static int InsertImg(string connectionString,string strSQL, byte[] fs)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
MySqlParameter myParameter = new MySqlParameter("@fs",MySqlDbType.LongBlob);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
public static Image LoadImg(int id)
{
using (MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection())
{
conn.ConnectionString = connstring;
conn.Open();
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select id,picture from sortlist where id =" + id ;
cmd.Connection = conn;
System.Data.Common.DbDataReader reader = cmd.ExecuteReader();
byte[] buffer = null;
if (reader.HasRows)
{
reader.Read();
long len = reader.GetBytes(1, 0, null, 0, 0);//1是picture
buffer = new byte[len];
len = reader.GetBytes(1, 0, buffer, 0, (int)len);
System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
System.Drawing.Image iamge = System.Drawing.Image.FromStream(ms);
return iamge;
}
}
return null;
}
这是最终的图