2016-07-22 78 views
1

我一直在谷歌上搜索这个,但我还没有找到任何好的解释,所以这是我的问题。从文件夹导入图像到SQL Server表

我需要导入产品映像,这些映像位于SQL Server的文件夹中,我尝试使用xp_cmdshell但未成功。

我的图片在C:\users\user.name\Images和图像有自己的名字作为产品ID,就像[product_id].jpg,他们打算与产品ID和图像二值作为列的表中插入。

我只需要列出文件夹上的图像,图像转换为二进制,并与文件名中插入他们在表(作为product_id

我的问题是:

  • 如何我要列出文件夹中的图像?
  • 我如何访问与点的文件夹中的名称(如user.name
  • 如何将图像转换为二进制文件,以便将它们存储在数据库(如SQL Server不会自动做)

在此先感谢

+1

可能还有其他的方法可以做到这一点,但我认为SSIS包会适合你。检查了这一点... http://blogs.lessthandot.com/index.php/datamgmt/dbprogramming/ssis-import-images-table/ – nscheaffer

+0

感谢您编辑文本@marc_s –

回答

1

我想我只是尝试了xp_cmdshell为基础的办法踢。我想出了一些看起来对我有用的东西,所以我很想知道当您尝试使用xp_cmdshell时遇到了什么问题。请参阅评论以获取此处发生的情况的解释。

-- I'm going to assume you already have a destination table like this one set up. 
create table Images (fname nvarchar(max), data varbinary(max)); 
go 

-- Set the directory whose images you want to load. The rest of this code assumes that @directory 
-- has a terminating backslash. 
declare @directory nvarchar(max) = N'D:\Images\'; 

-- Query the names of all .JPG files in the given directory. The dir command's /b switch omits all 
-- data from the output save for the filenames. Note that directories can contain single-quotes, so 
-- we need the REPLACE to avoid terminating the string literal too early. 
declare @filenames table (fname varchar(max)); 
declare @shellCommand nvarchar(max) = N'exec xp_cmdshell ''dir ' + replace(@directory, '''', '''''') + '*.jpg /b'''; 
insert @filenames exec(@shellCommand); 

-- Construct and execute a batch of SQL statements to load the filenames and the contents of the 
-- corresponding files into the Images table. I found when I called dir /b via xp_cmdshell above, I 
-- always got a null back in the final row, which is why I check for fname IS NOT NULL here. 
declare @sql nvarchar(max) = ''; 
with EscapedNameCTE as (select fname = replace(@directory + fname, '''', '''''') from @filenames where fname is not null) 
select 
    @sql = @sql + N'insert Images (fname, data) values (''' + E.fname + ''', (select X.* from openrowset(bulk ''' + E.fname + N''', single_blob) X)); ' 
from 
    EscapedNameCTE E; 
exec(@sql); 

我以空表Images开始。下面是我在运行上面后出现:

Images table contents

现在,我不是说这一定是去这样做的最佳方式;由@nscheaffer提供的链接可能更合适,我会自己阅读它,因为我不熟悉SSIS。但也许这将有助于说明你最初尝试的方式。

+0

实际上'xp_cmdshell'的问题是带有“。”的文件夹在他们的名字,如“user.name”。 我已经设法用'xp_dirtree'来完成它,将结果添加到#temp中,然后用光标遍历它。这是它里面的代码: set @ sql ='(SELECT img.bulkcolumn FROM OPENROWSET(BULK'''+ @ img +''',SINGLE_BLOB)AS img)' exec sp_executesql @sql 有了这个,我得到了在我的桌子上插入二进制文件! 我还检查您的解决方案,并在这里工作,所以我检查它作为正确=) –

+0

不得不分开“@”,从变量名,因为栈认为它是一提= d –

+0

我忘了这个问题,对不起你们。 我解决了我的问题,使用C#获取图像及其二进制文件,然后将其插入数据库,这很容易。 但我标记这个答案是正确的,因为它真的解决了这个问题=) 谢谢大家,很抱歉花了这么长时间回答 –