在mysql中有一个表   
CREATE
TABLE db_image
(
Id int(11) NOT NULL AUTO_INCREMENT,
FImage longblob,
PRIMARY KEY USING BTREE (Id)
)
ENGINE= InnoDB DEFAULT CHARSET= gb2312
c#中获取某个图片,然后写入mysql中的时候,image字段总是null。    
  我使用了mysql   connector/net   
C# code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data;
using MySql.Data.Types;
using MySql.Data.MySqlClient;
using System.IO;
using System.Data;
public partial class UpPhoto : System.Web.UI.Page
{
      protected void Page_Load(object sender, EventArgs e)
      {
      }
      protected void btnAdd_Click(object sender, EventArgs e)
      {
            //获得图象并把图象转换为byte[] 
            HttpPostedFile upPhoto = UpPhoto1.PostedFile;
            int upPhotoLength = upPhoto.ContentLength;
            byte[] PhotoArray = new Byte[upPhotoLength];
            Stream PhotoStream = upPhoto.InputStream;
            PhotoStream.Read(PhotoArray, 0, upPhotoLength);
            //连接数据库 
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = "User Id=sa;Host=localhost;Database=test";
            string strSql=string.Format("Insert into db_image(FImage) values(@FImage)");
            MySqlCommand cmd = new MySqlCommand(strSql, conn);
            cmd.Parameters.Add("@FImage", MySqlDbType.Byte);
            cmd.Parameters["@FImage"].Value = PhotoArray;
            conn.Open();
            try
            {
                  cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                  throw ex;
            }
            finally
            {
                  conn.Close();
            }
      }
      protected void btnShow_Click(object sender, EventArgs e)
      {
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = "User Id=sa;Host=localhost;Database=test";
            string strSql = "select * from db_image where id=1";//这里假设获取id为2的图片 
            MySqlCommand cmd = new MySqlCommand(strSql, conn);
            conn.Open();
            MySqlDataReader reader = cmd.ExecuteReader();
            reader.Read();
            Response.ContentType = "application/octet-stream";
            Response.BinaryWrite((Byte[])reader["FImage"]);
            Response.End();
            reader.Close();
      }
}
 --转自 
