C#将图片存入SQLServer数据库并读取

 

C#将图片存入SQLServer数据库并读取 

开发工具:Visual Studio.NET 2003,编程语言:C#,数据库:SQLServer2000
ASP.NET项目结构:项目名称:lianxi,lianxi下包括一页面文件InsertPicIntoSQLServer.aspx,一个文件夹PhotoTemp,一张图片1.gif

程序示例:
private SqlConnection conn=new SqlConnection();
private SqlCommand cmd=new SqlCommand();

1、插入数据库:
//初始化Connection对象
conn.ConnectionString=ConfigurationSettings.AppSettings["ConnectionString"];
conn.Open();
//初始化Command对象
cmd.Connection=conn;
cmd.CommandText="Insert into PICS(ID,PIC) values(1,@pic)";
//定义二进制数组
byte[] imagebyte=new byte[1048576];//大小为1MB
//定义文件流
FileStream imageStream=new FileStream(Server.MapPath("01.gif"),FileMode.Open,FileAccess.Read);
//通过文件流读取图片
imageStream.Read(imagebyte,0,1048576);
//给CommondText添加属性
cmd.Parameters.Add("@pic",SqlDbType.Image,(int)(imageStream.Length));
cmd.Parameters["@pic"].Value=imagebyte;
cmd.ExecuteNonQuery();
conn.Close();

2、读取数据库:
//初始化Connection对象
conn.ConnectionString=ConfigurationSettings.AppSettings["ConnectionString"];
conn.Open();
//初始化Command对象
cmd.Connection=conn;
cmd.CommandText="Select PIC from PICS where ID=1";
//创建DataReader对象
SqlDataReader dr=cmd.ExecuteReader();
try
{
dr.Read();
MemoryStream imagebuf=new MemoryStream((byte[])dr[0]);
//生成Image对象
System.Drawing.Image outImage=System.Drawing.Image.FromStream(imagebuf,true);
outImage.Save(Server.MapPath("PhotoTemp/")+"2.gif");
}
catch
{
}
dr.Close();
conn.Close();

没有更多推荐了,返回首页