2016-07-22 35 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#獲取圖像及其二進制文件,然後將其插入數據庫,這很容易。 但我標記這個答案是正確的,因爲它真的解決了這個問題=) 謝謝大家,很抱歉花了這麼長時間回答 –