private void button1_Click(object sender, System.EventArgs e)
{
FileStream fs = new FileStream("遗迹.jpg",FileMode.Open,FileAccess.Read);
byte[] bytes = new byte[fs.Length];
fs.Read(bytes,0,(int)fs.Length);
string sql = "insert TestFiles(MyFileName,FileType,MyFile)values(@FN,@FT,@MF)";
SqlCommand com = new SqlCommand(sql,this.sqlCon);
SqlParameter FN = new SqlParameter("@FN",SqlDbType.VarChar);
FN.Value = "遗迹";
com.Parameters.Add(FN);
SqlParameter FT = new SqlParameter("@FT",SqlDbType.VarChar);
FT.Value = "JPG";
com.Parameters.Add(FT);
SqlParameter MF = new SqlParameter("@MF",SqlDbType.Image);
MF.Value = bytes;
com.Parameters.Add(MF);
com.CommandType = CommandType.Text;

sqlCon.ConnectionString  = this.conStr;
try
{
sqlCon.Open();
com.ExecuteNonQuery();
sqlCon.Close();
MessageBox.Show("存入成功!");
}
catch(Exception ex)
{
throw ex;
}
finally
{
sqlCon.Close();
}
} private void button2_Click(object sender, System.EventArgs e)
{
string sql = "select MyFile from TestFiles where id = 1";

sqlCon.ConnectionString = this.conStr; SqlCommand readComm = new SqlCommand(sql,this.sqlCon); SqlDataReader dr = null; FileStream fs = null; BinaryWriter bw = null; int bufferSize = 100;  byte[] outbyte = new byte[bufferSize]; long retval;  long startIndex = 0;
try
{
sqlCon.Open();
dr = readComm.ExecuteReader();
while(dr.Read())
{
fs = new FileStream("TakeOut.jpg",FileMode.OpenOrCreate,FileAccess.Write); bw = new BinaryWriter(fs); retval = dr.GetBytes(0, startIndex, outbyte, 0, bufferSize);

while (retval == bufferSize)
{
bw.Write(outbyte);
bw.Flush();

startIndex += bufferSize;
retval = dr.GetBytes(0, startIndex, outbyte, 0, bufferSize);
} // Write the remaining buffer.
bw.Write(outbyte, 0, (int)retval - 1);
bw.Flush(); // Close the output file.
bw.Close();
fs.Close();

Image im = Image.FromFile("TakeOut.jpg"); this.pictureBox1.Image = im;
}
sqlCon.Close();
}
catch(Exception ex)
{
throw ex;
}
finally
{
sqlCon.Close();
bw.Close();
fs.Close();
}
}

解决方案 »

  1.   

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TestFiles]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[TestFiles]
    GOCREATE TABLE [dbo].[TestFiles] (
    [id] [int] IDENTITY (1, 1) NOT NULL ,
    [MyFileName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
    [FileType] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
    [MyFile] [image] NOT NULL 
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    GO
      

  2.   

    http://dotnet.aspx.cc/ShowList.aspx?id=1
      

  3.   

    http://authors.aspalliance.com/das/tutorial/test/datagridimages.aspx
    http://authors.aspalliance.com/das/datagridimages.html