How to access SQL Server FileStream with progress
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 ''' <summary> ''' 将文件保存到数据库 ''' </summary> ''' <param name="conn">数据库连接</param> ''' <param name="name">名称</param> ''' <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 '事务 Dim transaction As SqlTransaction = conn.BeginTransaction("mainTranaction") sqlCmd.Transaction = transaction '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 '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 '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 ''' <summary> ''' 从数据库读取数据保存到文件 ''' </summary> ''' <param name="conn">数据库连接</param> ''' <param name="name">名称</param> ''' <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 '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 '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 '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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This website reported on March 7 that Dr. Zhou Yuefeng, President of Huawei's Data Storage Product Line, recently attended the MWC2024 conference and specifically demonstrated the new generation OceanStorArctic magnetoelectric storage solution designed for warm data (WarmData) and cold data (ColdData). Zhou Yuefeng, President of Huawei's data storage product line, released a series of innovative solutions. Image source: Huawei's official press release attached to this site is as follows: The cost of this solution is 20% lower than that of magnetic tape, and its power consumption is 90% lower than that of hard disks. According to foreign technology media blocksandfiles, a Huawei spokesperson also revealed information about the magnetoelectric storage solution: Huawei's magnetoelectronic disk (MED) is a major innovation in magnetic storage media. First generation ME

Vue3+TS+Vite development tips: How to encrypt and store data. With the rapid development of Internet technology, data security and privacy protection are becoming more and more important. In the Vue3+TS+Vite development environment, how to encrypt and store data is a problem that every developer needs to face. This article will introduce some common data encryption and storage techniques to help developers improve application security and user experience. 1. Data Encryption Front-end Data Encryption Front-end encryption is an important part of protecting data security. Commonly used

What is cache? A cache (pronounced ka·shay) is a specialized, high-speed hardware or software component used to store frequently requested data and instructions, which in turn can be used to load websites, applications, services, and other aspects of the system faster part. Caching makes the most frequently accessed data readily available. Cache files are not the same as cache memory. Cache files refer to frequently needed files such as PNGs, icons, logos, shaders, etc., which may be required by multiple programs. These files are stored in your physical drive space and are usually hidden. Cache memory, on the other hand, is a type of memory that is faster than main memory and/or RAM. It greatly reduces data access time since it is closer to the CPU and faster compared to RAM

Git is a fast, reliable, and adaptable distributed version control system. It is designed to support distributed, non-linear workflows, making it ideal for software development teams of all sizes. Each Git working directory is an independent repository with a complete history of all changes and the ability to track versions even without network access or a central server. GitHub is a Git repository hosted on the cloud that provides all the features of distributed revision control. GitHub is a Git repository hosted on the cloud. Unlike Git which is a CLI tool, GitHub has a web-based graphical user interface. It is used for version control, which involves collaborating with other developers and tracking changes to scripts and

How to correctly use sessionStorage to store sensitive information requires specific code examples. Whether in web development or mobile application development, we often need to store and process sensitive information, such as user login credentials, ID numbers, etc. In front-end development, using sessionStorage is a common storage solution. However, since sessionStorage is browser-based storage, some security issues need to be paid attention to to ensure that the stored sensitive information is not maliciously accessed and used.

Microsoft SQL Server is a relational database management system launched by Microsoft. It is a comprehensive database platform that uses integrated business intelligence (BI) tools to provide enterprise-level data management. It is easy to use, has good scalability, and has a high degree of integration with related software. High advantages. The SQL Server database engine provides more secure and reliable storage functions for relational data and structured data, allowing users to build and manage highly available and high-performance data applications for business.

How do PHP and swoole achieve efficient data caching and storage? Overview: In web application development, data caching and storage are a very important part. PHP and swoole provide an efficient method to cache and store data. This article will introduce how to use PHP and swoole to achieve efficient data caching and storage, and give corresponding code examples. 1. Introduction to swoole: swoole is a high-performance asynchronous network communication engine developed for PHP language. It can

This article is reprinted from the WeChat public account "Living in the Information Age". The author lives in the information age. To reprint this article, please contact the Living in the Information Age public account. For students who are familiar with database operations, writing beautiful SQL statements and finding ways to find the data they need from the database is a routine operation. For students who are familiar with machine learning, it is also a routine operation to obtain data, preprocess the data, build a model, determine the training set and test set, and use the trained model to make a series of predictions about the future. So, can we combine the two technologies? We see that data is stored in the database, and predictions need to be based on past data. If we query future data through the existing data in the database, then it is
