• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

该例子是一个对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

转载于:https://www.cnblogs.com/andrew-blog/archive/2011/12/03/CSharp_SQL_Image.html


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap