有人问到图片如何存储到数据库中,以前也做过,但年代已有点久远,选择使用的软件都升级了,有些东西已废弃。所以花了点时间用VS2008+SQL Server 2005做了一个测试程序,希望能对人有所帮助。与人玫瑰,手有余香。涉及到存储过程,ADO.NET操纵数据库,SQL Server 2005中的image(或varbinary(max))字段使用。
在SQL Server 2005中建立数据库、表、存储过程,SQL如下:
create database test
go
use test
create table tblImage(
[id] int identity(1,1) primary key,
picture varbinary(max))--或picture image
go
--插入图片到数据库表中的varbinary(max)类型(或image)的存储过程,需要文件名及表名参数(有默认值,可不提供此参数)
create proc spInsertImage(@fileName nvarchar(100), @tableName nvarchar(20)='tblImage') as
begin
set nocount on
declare @sql nvarchar(max)
set @sql='insert into ' + @tableName +
' select * from OPENROWSET (bulk ''' + @fileName +''', SINGLE_BLOB) as myTable'