gpt4 book ai didi

sql-server - 将文件夹中的图像导入 SQL Server 表

转载 作者:行者123 更新时间:2023-12-04 02:10:54 27 4
gpt4 key购买 nike

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

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

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

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

我的问题是:

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

  • 提前致谢

    最佳答案

    我想我会尝试一个 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 开始 table 。这是我在运行上述后的结果:

    Images table contents

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

    关于sql-server - 将文件夹中的图像导入 SQL Server 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38533074/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com