SQL Server 2000中的ntext、text 和 image数据类型用于存储大型非 Unicode 字符、Unicode 字符及二进制数据的固定长度和可变长度数据类型。其中image可变长度二进制数据介于 0 与 231-1 (2,147,483,647) 字节之间。对于上述三种数据的存取一直是使用SQL Server2000 的一个难点。本实验实现在.NET平台下对SQL Server 2000 Image类型数据的存取操作。
关键代码解析
1、存储图片
//第一步:建立并打开文件流
FileStream fs = File.Open(this.openFileDialog1.FileName,FileMode.Open
,FileAccess.Read,FileShare.None);
//第二步:声明byte型数组
byte [] b = new byte[fs.Length];
//第三步:读取文件内容
fs.Read(b,0,(int)b.Length);
fs.Close();
/*
* 存储一张图片到SQL 2000数据库
* 操作方式与存储一般数据相类似
* */
//第四步:建立、打开数据库连接
SqlConnection con = new SqlConnection("server =.;database = bdqn;uid = sa;pwd = sa;");
con.Open();
//第五步:实例化Command对象
SqlCommand com = con.CreateCommand();
com.CommandText="insert into p (pic)values(@pic/*@pic 是存储过程参数*/)";
//为SqlCommand对象的SqlParameter 对象添加@pic属性
SqlParameter sp =new SqlParameter("@pic",SqlDbType.Image);
sp.Direction = ParameterDirection.Input;
sp.Value = b;
com.Parameters.Add(sp);
//执行操作
com.ExecuteNonQuery();
con.Close();
2、读取图片
private void button2_Click(object sender, System.EventArgs e)
{
SqlConnection con = new SqlConnection("server =.;database = bdqn;uid = sa;pwd = sa;");
con.Open();
SqlCommand com = con.CreateCommand();
com.CommandText="select pic from p where id = 1";
//强制转换为byte【】数组
byte []b = (byte[])com.ExecuteScalar();
con.Close();
//通过MemoryStream流实例化Image对象
MemoryStream ms = new MemoryStream(b,0,(int)b.Length);
this.pictureBox1.Image = Image.FromStream(ms);
}