search
HomeDatabaseMysql TutorialHow to access SQL Server FileStream with progress
How to access SQL Server FileStream with progressJun 15, 2018 am 09:21 AM
sql serverstorage

Detailed reference to the SQL Server FileStream function online help design and implementation of FILESTREAM storage
Here is just an adjustment of the code that uses Win32 to manage FILESTREAM data to achieve progressed access, which is more suitable for accessing larger files. Significant
To use FileStream, first turn on the FileStream option in SQL Server Configuration Manager: SQL Server Configuration Manager – SQL Server Service – Find SQL Server Service – Properties – FILESTREAM – Allow remote clients to access FILESTREAM data as needed in the service list on the right Select, select both other recommendations. After the configuration is completed, you need to restart the SQL Server service for the settings to take effect.
Then use the following script to create the test database and test table

 -- =========================================================-- 启用 filestream_access_level-- =========================================================EXEC sp_configure 'filestream_access_level', 2;     -- 0=禁用  1=针对 T-SQL 访问启用 FILESTREAM  2=针对 T-SQL 和 WIN32 流访问启用 FILESTREAMRECONFIGURE;
GO-- =========================================================-- 创建测试数据库-- =========================================================EXEC master..xp_create_subdir 'f:\temp\db\_test';CREATE DATABASE _testON
    PRIMARY(
        NAME = _test, FILENAME = 'f:\temp\db\_test\_test.mdf'),
    FILEGROUP FG_stream CONTAINS FILESTREAM(
        NAME = _test_file_stream, FILENAME = 'f:\temp\db\_test\stream')
    LOG ON(
        NAME = _test_log, FILENAME = 'f:\temp\db\_test\_test.ldf')
;GO-- =========================================================-- FileStream-- =========================================================-- =================================================-- 创建 包含 FileStream 数据的表-- -------------------------------------------------CREATE TABLE _test.dbo.tb_fs(
    id uniqueidentifier ROWGUIDCOL      -- 必需        DEFAULT NEWSEQUENTIALID ( ) PRIMARY KEY,
    name nvarchar(260),
    content varbinary(max) FILESTREAM
);GO
下面的 VB 脚本实现带进度显示的文件存(Write方法)取(Read方法)
Imports System.IO
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Module Module1
    Public Sub Main(ByVal args As String())
        Dim sqlConnection As New SqlConnection("Integrated Security=true;server=localhost")
        Try
            sqlConnection.Open()
            Console.WriteLine("将文件保存到 FileStream")
            Write(sqlConnection, "test", "f:\temp\re.csv")
            Console.WriteLine("从 FileStream 读取数据保存到文件")
            Read(sqlConnection, "test", "f:\temp\re_1.csv")
        Catch ex As System.Exception
            Console.WriteLine(ex.ToString())
        Finally
            sqlConnection.Close()        End Try
        Console.WriteLine("处理结束,按 Enter 退出")
        Console.ReadLine()    End Sub    &#39;&#39;&#39; <summary>
    &#39;&#39;&#39; 将文件保存到数据库    &#39;&#39;&#39; </summary>
    &#39;&#39;&#39; <param name="conn">数据库连接</param>    &#39;&#39;&#39; <param name="name">名称</param>
    &#39;&#39;&#39; <param name="file">文件名</param>
    Sub Write(ByVal conn As SqlConnection, ByVal name As String, ByVal file As String)
        Dim bufferSize As Int32 = 1024
        Using sqlCmd As New SqlCommand
            sqlCmd.Connection = conn            &#39;事务
            Dim transaction As SqlTransaction = conn.BeginTransaction("mainTranaction")
            sqlCmd.Transaction = transaction
            &#39;1. 读取 FILESTREAM 文件路径 ( 注意函数大小写 )
            sqlCmd.CommandText = "
UPDATE _test.dbo.tb_fs SET content = 0x WHERE name = @name;
IF @@ROWCOUNT = 0 INSERT _test.dbo.tb_fs(name, content) VALUES( @name, 0x );
SELECT content.PathName() FROM _test.dbo.tb_fs WHERE name = @name;"
            sqlCmd.Parameters.Add(New SqlParameter("name", name))
            Dim filePath As String = Nothing
            Dim pathObj As Object = sqlCmd.ExecuteScalar()            If Not pathObj.Equals(DBNull.Value) Then
                filePath = DirectCast(pathObj, String)            Else
                Throw New System.Exception("content.PathName() failed to read the path name for the content column.")            End If
            &#39;2. 读取当前事务上下文
            sqlCmd.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()"
            Dim obj As Object = sqlCmd.ExecuteScalar()
            Dim txContext As Byte() = Nothing
            Dim contextLength As UInteger
            If Not obj.Equals(DBNull.Value) Then
                txContext = DirectCast(obj, Byte())
                contextLength = txContext.Length()
            Else
                Dim message As String = "GET_FILESTREAM_TRANSACTION_CONTEXT() failed"
                Throw New System.Exception(message)
            End If
            &#39;3. 获取 Win32 句柄,并使用该句柄在 FILESTREAM BLOB 中读取和写入数据            Using sqlFileStream As New SqlFileStream(filePath, txContext, FileAccess.Write)
                Dim buffer As Byte() = New Byte(bufferSize - 1) {}
                Dim numBytes As Integer = 0
                Using fsRead As New FileStream(file, FileMode.Open)
                    While True
                        numBytes = fsRead.Read(buffer, 0, bufferSize)                        If numBytes = 0 Then Exit While
                        sqlFileStream.Write(buffer, 0, numBytes)
                        Console.WriteLine(String.Format("{0} -> {1} -> {2}", fsRead.Position, sqlFileStream.Position, numBytes))                    End While
                    fsRead.Close()                End Using
                sqlFileStream.Close()            End Using
            sqlCmd.Transaction.Commit()        End Using
    End Sub    &#39;&#39;&#39; <summary>
    &#39;&#39;&#39; 从数据库读取数据保存到文件    &#39;&#39;&#39; </summary>
    &#39;&#39;&#39; <param name="conn">数据库连接</param>    &#39;&#39;&#39; <param name="name">名称</param>
    &#39;&#39;&#39; <param name="file">文件名</param>
    Sub Read(ByVal conn As SqlConnection, ByVal name As String, ByVal file As String)
        Dim bufferSize As Int32 = 1024
        Using sqlCmd As New SqlCommand
            sqlCmd.Connection = conn            &#39;1. 读取 FILESTREAM 文件路径 ( 注意函数大小写 )
            sqlCmd.CommandText = "SELECT content.PathName() FROM _test.dbo.tb_fs WHERE name = @name;"
            sqlCmd.Parameters.Add(New SqlParameter("name", name))
            Dim filePath As String = Nothing
            Dim pathObj As Object = sqlCmd.ExecuteScalar()
            If Not pathObj.Equals(DBNull.Value) Then
                filePath = DirectCast(pathObj, String)
            Else
                Throw New System.Exception("content.PathName() failed to read the path name for the content column.")
            End If
            &#39;2. 读取当前事务上下文
            Dim transaction As SqlTransaction = conn.BeginTransaction("mainTranaction")
            sqlCmd.Transaction = transaction
            sqlCmd.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()"
            Dim obj As Object = sqlCmd.ExecuteScalar()
            Dim txContext As Byte() = Nothing
            Dim contextLength As UInteger            If Not obj.Equals(DBNull.Value) Then
                txContext = DirectCast(obj, Byte())
                contextLength = txContext.Length()            Else
                Dim message As String = "GET_FILESTREAM_TRANSACTION_CONTEXT() failed"
                Throw New System.Exception(message)            End If
            &#39;3. 获取 Win32 句柄,并使用该句柄在 FILESTREAM BLOB 中读取和写入数据
            Using sqlFileStream As New SqlFileStream(filePath, txContext, FileAccess.Read)
                Dim buffer As Byte() = New Byte(bufferSize - 1) {}
                Dim numBytes As Integer = 0
                Using fsRead As New FileStream(file, FileMode.Create)
                    While True
                        numBytes = sqlFileStream.Read(buffer, 0, bufferSize)
                        If numBytes = 0 Then Exit While
                        fsRead.Write(buffer, 0, numBytes)
                        Console.WriteLine(String.Format("{0} -> {1} -> {2}", sqlFileStream.Position, sqlFileStream.Position, numBytes))
                    End While
                    fsRead.Close()
                End Using
                sqlFileStream.Close()
            End Using
            sqlCmd.Transaction.Commit()
        End Using
    End Sub
End Module

This article explains how to access SQL Server FileStream with progress. For more related content, please pay attention to the php Chinese website.

Related recommendations:

What to do when you forget the SQL Server administrator password

A brief analysis of concat and group_concat in MySQL Use

#Introduction to MySQL graphical management tool

The above is the detailed content of How to access SQL Server FileStream with progress. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
如何在 Windows 11 上清理缓存:详细的带图片教程如何在 Windows 11 上清理缓存:详细的带图片教程Apr 24, 2023 pm 09:37 PM

什么是缓存?缓存(发音为ka·shay)是一种专门的高速硬件或软件组件,用于存储经常请求的数据和指令,这些数据和指令又可用于更快地加载网站、应用程序、服务和系统的其他部分。缓存使最常访问的数据随时可用。缓存文件与缓存内存不同。缓存文件是指经常需要的文件,如PNG、图标、徽标、着色器等,多个程序可能需要这些文件。这些文件存储在您的物理驱动器空间中,通常是隐藏的。另一方面,高速缓存内存是一种比主内存和/或RAM更快的内存类型。它极大地减少了数据访问时间,因为与RAM相比,它更靠近CPU并且速度

microsoft sql server是什么软件microsoft sql server是什么软件Feb 28, 2023 pm 03:00 PM

microsoft sql server是Microsoft公司推出的关系型数据库管理系统,是一个全面的数据库平台,使用集成的商业智能(BI)工具提供了企业级的数据管理,具有使用方便可伸缩性好与相关软件集成程度高等优点。SQL Server数据库引擎为关系型数据和结构化数据提供了更安全可靠的存储功能,使用户可以构建和管理用于业务的高可用和高性能的数据应用程序。

PHP和swoole如何实现高效的数据缓存和存储?PHP和swoole如何实现高效的数据缓存和存储?Jul 23, 2023 pm 04:03 PM

PHP和swoole如何实现高效的数据缓存和存储?概述:在Web应用开发中,数据的缓存和存储是非常重要的一部分。而PHP和swoole提供了一种高效的方法来实现数据的缓存与存储。本文将介绍如何使用PHP和swoole来实现高效的数据缓存和存储,并给出相应的代码示例。一、swoole简介:swoole是一个针对PHP语言开发的,高性能的异步网络通信引擎,它可以

一文读懂人工智能表:从MindsDB说起一文读懂人工智能表:从MindsDB说起Apr 12, 2023 pm 12:04 PM

本文转载自微信公众号「活在信息时代」,作者活在信息时代。转载本文请联系活在信息时代公众号。对于熟悉数据库操作的同学来说,编写优美的SQL语句,从数据库中想方设法找出自己需要的数据,是常规操作了。而对于熟悉机器学习的同学来说,获取数据,对数据进行预处理,建立模型,确定训练集和测试集,用训练好的模型对未来进行一系列的预测,也是一种常规操作了。那么,我们能否将两种技术结合起来呢?我们看到数据库里存储了数据,而进行预测需要基于以往的数据。如果我们通过数据库里现有的数据,对于未来的数据进行查询的话,那么是

使用PHP数组实现数据缓存和存储的方法和技巧使用PHP数组实现数据缓存和存储的方法和技巧Jul 16, 2023 pm 02:33 PM

使用PHP数组实现数据缓存和存储的方法和技巧随着互联网的发展和数据量的急剧增长,数据缓存和存储成为了我们在开发过程中必须要考虑的问题之一。PHP作为一门广泛应用的编程语言,也提供了丰富的方法和技巧来实现数据缓存和存储。其中,使用PHP数组进行数据缓存和存储是一种简单而高效的方法。一、数据缓存数据缓存的目的是为了减少对数据库或其他外部数据源的访问次数,从而提高

SQL Server还是MySQL?最新研究揭秘最佳数据库选择。SQL Server还是MySQL?最新研究揭秘最佳数据库选择。Sep 08, 2023 pm 04:34 PM

SQLServer还是MySQL?最新研究揭秘最佳数据库选择近年来,随着互联网和大数据的快速发展,数据库的选择成为了企业和开发者们面临的一个重要问题。在众多数据库中,SQLServer和MySQL作为两个最为常见和广泛使用的关系型数据库,备受争议。那么,在SQLServer和MySQL之间,到底应该选择哪一个呢?最新的研究为我们揭示了这个问题。首先,让

PHP和SQL Server数据库开发PHP和SQL Server数据库开发Jun 20, 2023 pm 10:38 PM

随着互联网的普及,网站和应用程序的开发成为了许多企业和个人的主要业务。而PHP和SQLServer数据库则是其中非常重要的两个工具。PHP是一种服务器端脚本语言,可以用于开发动态网站;SQLServer是微软公司开发的关系型数据库管理系统,具有广泛的应用场景。在本文中,我们将讨论PHP和SQLServer的开发,以及它们的优缺点和应用方法。首先,让我们

如何使用PDO连接到Microsoft SQL Server数据库如何使用PDO连接到Microsoft SQL Server数据库Jul 29, 2023 pm 01:49 PM

如何使用PDO连接到MicrosoftSQLServer数据库介绍:PDO(PHPDataObjects)是PHP提供的一个访问数据库的统一接口。它提供了许多优点,比如实现了数据库的抽象层,可以方便地切换不同的数据库类型,而不需要修改大量的代码。本文将介绍如何使用PDO连接到MicrosoftSQLServer数据库,并提供一些相关代码示例。步骤

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools