如何使用SQL查询从表中检索图像并将其保存到其他服务器的文件夹中

时间:2018-08-28 06:20:14

标签: sql sql-server

如何使用SQL查询从表中检索图像并将其保存到其他服务器的文件夹中 图像以BLOB的形式存储在DB中。

3 个答案:

答案 0 :(得分:0)

不能单独使用SQL Server执行文件系统操作。因此,如果要将SQL Server数据库中存储的图像另存为文件系统中的文件,请尝试使用C#或任何此类前端语言从数据库中检索记录,然后保存到所需位置

答案 1 :(得分:0)

您可以使用类似的方法。

-- This will create format file, replace [TABLE_NAME_WITH_DATABASE] with your table and [SERVERNAME] with your server name
EXEC xp_cmdshell 'bcp [TABLE_NAME_WITH_DATABASE] format null -S [SERVERNAME] -T -n -f c:\Test\PP.fmt' 

-- After this step you will see a format file,in that you have to delete all other columns except your image column
-- and run below query.
EXEC xp_cmdshell 'bcp "SELECT Photo FROM Server.Db.Table WHERE PK = 1" queryout C:\Test\ProductPhotoID_69.[IMAGE_EXTENSTION] -S [SERVERNAME] -T -f C:\Test\PP.fmt' 

答案 2 :(得分:0)

您可以使用PowerShell进行操作,下面是一个示例:

$connectionString = "Data Source=SERVER;Initial Catalog=DATABASE;pwd=PASSWORD;User ID=USER;"
$sqlCommandText = "SELECT id, Photo, Photo_TypeMime FROM MYTABLE" #query
$saveToDir = "D:\" # output directory
$connection = new-object System.Data.SqlClient.SQLConnection($connectionString)
$command = new-object System.Data.sqlclient.sqlcommand($sqlCommandText,$connection)
$connection.Open()
$bufferSize = 8192 #default value
$buffer = [array]::CreateInstance('Byte', $bufferSize)
$dr = $command.ExecuteReader()
While ($dr.Read())
{
    $ext = GetExtFromMimeType($dr.GetString(2)) # create a function to return extention from mime type if you don't have the file name saved in the database
    $fs = New-Object System.IO.FileStream($saveToDir + $dr.GetDecimal(0) + $ext), Create, Write #my example id is decimal but you can change it
    $bw = New-Object System.IO.BinaryWriter $fs
    $start = 0
    $received = $dr.GetBytes(1, $start, $buffer, 0, $bufferSize - 1)
    While ($received -gt 0)
    {
       $bw.Write($buffer, 0, $received)
       $bw.Flush()
       $start += $received
       # Read next byte stream
       $received = $dr.GetBytes(1, $start, $buffer, 0, $bufferSize - 1)
    }
    $bw.Close()
    $fs.Close()
}
$fs.Dispose()
$dr.Close()
$command.Dispose()
$connection.Close()

您还可以在此处找到更详细的示例:https://social.technet.microsoft.com/wiki/contents/articles/890.export-sql-server-blob-data-with-powershell.aspx