Insert image into SQL Server 2008 Express database

2019-08-15 03:06发布

I am working with test data in Visual Studio's server explorer. How would I put images into the database just as test images? I have no front end component built to take care of image uploading.

2条回答
孤傲高冷的网名
2楼-- · 2019-08-15 03:35

It will work for SQL server 2008r2...but first u have to create a filestream database.

//create databse

CREATE DATABASE Archive 
ON
PRIMARY ( NAME = Arch1,FILENAME = 'c:\data\archdat1.mdf'),
FILEGROUP FileStreamGroup1 CONTAINS FILESTREAM( NAME = Arch3,FILENAME = 'c:\data\filestream1')
LOG ON  ( NAME = Archlog1,FILENAME = 'c:\data\archlog1.ldf')
GO

//table creation

Use Archive
GO
CREATE TABLE [FileStreamDataStorage]
(
[ID] [INT] IDENTITY(1,1) NOT NULL,
[FileStreamData] VARBINARY(MAX) FILESTREAM NULL,
[FileStreamDataGUID] UNIQUEIDENTIFIER ROWGUIDCOL NOT NULL UNIQUE DEFAULT NEWSEQUENTIALID(),
[DateTime] DATETIME DEFAULT GETDATE()
)
ON [PRIMARY]
FILESTREAM_ON FileStreamGroup1
GO

//inserting value

Use Archive
GO
INSERT INTO [FileStreamDataStorage] (FileStreamData)
SELECT * FROM
OPENROWSET(BULK N'C:\Users\Public\Pictures\Sample Pictures\image1.jpg' ,SINGLE_BLOB) AS Document
GO
查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-15 03:36

You can upload an image into a db (and retrieve it) using byte[] as data type, assuming that in your db corresponding column is a BLOB.
So if you load your image with byte[] img = File.ReadAllBytes(your_file) then you can use a query like this INSERT INTO table SET image_col = @par, where par is a parameter whose value is img.

查看更多
登录 后发表回答