代码改变世界

C#操作SQL Server中的Image类型数据

2011-12-03 21:29  Andrew.Wangxu  阅读(616)  评论(0编辑  收藏  举报

该例子是一个对SQL Server数据类型的一个操作例子,具有写入、读取功能。

1:准备数据库

1)创建数据库 Test

2)创建表 Table_1 (分别有2个字段:id(Int)、photo(Image))

如图:

 

2:用C#进行读写操作,完整代码如下:

using System;  
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace imageTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btn_brewse_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "浏览图像文件";
op.Filter = "图像文件(*.jpg)|*.jpg";
op.ShowDialog();
txt_ImageAddress.Text = op.FileName;
}

private void btn_Insert_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(txt_ImageAddress.Text,FileMode.Open,FileAccess.Read);
byte[] byteArray = new byte[fs.Length];
fs.Read(byteArray,0,Convert.ToInt32(fs.Length));
fs.Close();

string connectionStr = "Server=.;Database=Test;Uid=sa;Pwd=123456";
SqlConnection conn = new SqlConnection(connectionStr);
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Table_1(photo) VALUES(@photo)",conn);
SqlParameter parmeter = new SqlParameter("@photo", SqlDbType.Image);
parmeter.Value = byteArray;
cmd.Parameters.Add(parmeter);
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("插入成功");
conn.Close();
}

private void btn_ReadImage_Click(object sender, EventArgs e)
{
string connectionStr = "Server=.;Database=Test;Uid=sa;Pwd=123456";
SqlConnection conn = new SqlConnection(connectionStr);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Table_1",conn);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
byte[] image = (byte[])dr["photo"];
conn.Close();
if (image.Length == 0)
return;
string photoUrl = Environment.CurrentDirectory + "\\1.jpg";
FileStream fs = new FileStream(photoUrl, FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.BaseStream.Write(image, 0, image.Length);
bw.Flush();
bw.Close();

picbox_image.ImageLocation = photoUrl;
}

}
}

 

效果如图:

完整项目(包含数据库文件):点击下载

参考:http://www.wxzzz.com/?id=47