将图像从文件夹导入 SQL Server 表

Dan*_*sta 4 sql-server

我一直在谷歌上搜索这个,但没有找到任何好的解释,所以这是我的问题。

我需要将产品图像导入 SQL Server 的文件夹中,我尝试使用xp_cmdshell但没有成功。

我的图像已在其中C:\users\user.name\Images,并且图像的名称作为产品 ID,就像[product_id].jpg它们将被插入到以产品 ID 和图像二进制文件作为列的表中一样。

我只需要列出文件夹中的图像,将图像转换为二进制并将它们插入到带有文件名的表中(如product_id

我的问题是:

  • 如何列出文件夹中的图像?
  • 如何访问名称中带有点的文件夹(例如user.name
  • 如何将图像转换为二进制以便将它们存储在数据库中(如果 SQL Server 没有自动执行此操作)

提前致谢

Joe*_*ell 5

我想我会尝试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);
Run Code Online (Sandbox Code Playgroud)

我从一张空桌子开始Images。这是我运行上述命令后得到的结果:

图像表内容

现在我并不是说这一定是最好的方法;而是说这一定是最好的方法。@nscheaffer 提供的链接可能更合适,我会自己阅读它,因为我不熟悉 SSIS。但这也许有助于说明您最初尝试的方法。