首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

新手!在C#中怎么将图片存到SQL中~

2012-01-28 
新手!在C#中如何将图片存到SQL中~!~如何将图片存入SQL中在线等待~!~!希望能把关键代码发上来谢谢~![解决办

新手!在C#中如何将图片存到SQL中~!~
如何将图片存入SQL中在线等待~!~!希望能把关键代码发上来谢谢~!

[解决办法]
using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;

class BLOBDemo
{
[STAThread]
static void Main(string[] args)
{
Add( "Test ", "1.jpg ");
}

public static void Add(string categoryName, string filePath)
{
//byte [] photo = GetPhoto(filePath);

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);

byte [] photo = br.ReadBytes((int)fs.Length);

br.Close();
fs.Close();

SqlConnection cn = new SqlConnection( "Data Source = (local);Integrated Security = SSPI;Initial Catalog=Northwind ");
SqlCommand cmd = new SqlCommand( "INSERT INTO Categories(CategoryName, Picture) VALUES (@CategoryName, @Picture) ", cn);

cmd.Parameters.Add( "@CategoryName ", SqlDbType.NVarChar, 15).Value = categoryName;
cmd.Parameters.Add( "@Picture ", SqlDbType.Image, photo.Length).Value = photo;

cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}

public static byte [] GetPhoto(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);

byte [] photo = br.ReadBytes((int)fs.Length);

br.Close();
fs.Close();

return photo;
}
}

热点排行