标题:SQL Server的图片存取
取消只看楼主
live41
Rank: 10Rank: 10Rank: 10
等 级:贵宾
威 望:67
帖 子:12442
专家分:0
注 册:2004-7-22
结帖率:66.67%
 问题点数:0 回复次数:1 
SQL Server的图片存取

由于比较多人问,问了又问,把我以前的代码共享一下。

using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;

// 下面是从数据库取出图片
try
{
string getPhoto = @"select photo from gch_Customer_Photo where customerID=1234";

DataSet ds = new DataSet();
sqlDataAdapter1 = new SqlDataAdapter(getPhoto, sqlConnection1);
sqlDataAdapter1.Fill(ds);

DataRow row = ds.Tables[0].Rows[0];
byte[] bPhoto = new byte[0];
bPhoto = (byte[])row["photo"];
//int arraySize = bPhoto.GetUpperBound(0);

MemoryStream memstr = new MemoryStream(bPhoto);
pictureBox1.Image = Image.FromStream(memstr, true);

existPhoto==true
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}

// 下面是将图片存入数据库

OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "*.bmp;*.jpg;*.gif|*.bmp;*.jpg;*.gif;*.jpeg";
if(ofd.ShowDialog()==DialogResult.OK)
{
string filePath = ofd.FileName;

FileInfo imageFile = new FileInfo(filePath);
if(imageFile.Length > 204800)
{
Console.WriteLine("图片大小最好不要过大!");
}

pictureBox1.Image = Image.FromFile(filePath);

if(existPhoto==true)
{ //如果之前已有图片,可以考虑删除了旧的先
string deleteOld = @"delete from gch_Customer_Photo where customerID=1234";
SqlCommand sqlcmmd = new SqlCommand(deleteOld,sqlConnection1);
sqlcmmd.ExecuteNonQuery();
}

string getAllPhotos = @"select customerID, photo from gch_Customer_Photo";

DataSet ds = new DataSet();
sqlDataAdapter1 = new SqlDataAdapter(getAllPhotos,sqlConnection1);
sqlDataAdapter1.MissingSchemaAction = MissingSchemaAction.AddWithKey;

FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read);

byte[] bPhoto= new byte[fs.Length];
fs.Read(bPhoto, 0, System.Convert.ToInt32(fs.Length));
fs.Close();

sqlDataAdapter1.Fill(ds);

DataRow oneRow = ds.Tables[0].NewRow();
oneRow["customerID"] = 1234;
oneRow["photo"] = bPhoto;
ds.Tables[0].Rows.Add(oneRow);

sqlDataAdapter1.Update(ds);

Console.WriteLine("图片入库成功!");
}

[此贴子已经被作者于2006-12-2 13:31:19编辑过]

搜索更多相关主题的帖子: SQL Server 数据库 using System 
2006-12-02 13:29
live41
Rank: 10Rank: 10Rank: 10
等 级:贵宾
威 望:67
帖 子:12442
专家分:0
注 册:2004-7-22
得分:0 
不行,用Message不够ToString好,原因是……

你自己想吧。

2006-12-02 13:52



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-106766-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.086213 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved