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!

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

Use the EXPLAIN command to analyze the execution plan of MySQL queries. 1. The EXPLAIN command displays the execution plan of the query to help find performance bottlenecks. 2. The execution plan includes fields such as id, select_type, table, type, possible_keys, key, key_len, ref, rows and Extra. 3. According to the execution plan, you can optimize queries by adding indexes, avoiding full table scans, optimizing JOIN operations, and using overlay indexes.

Subqueries can improve the efficiency of MySQL query. 1) Subquery simplifies complex query logic, such as filtering data and calculating aggregated values. 2) MySQL optimizer may convert subqueries to JOIN operations to improve performance. 3) Using EXISTS instead of IN can avoid multiple rows returning errors. 4) Optimization strategies include avoiding related subqueries, using EXISTS, index optimization, and avoiding subquery nesting.

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

Renaming a database in MySQL requires indirect methods. The steps are as follows: 1. Create a new database; 2. Use mysqldump to export the old database; 3. Import the data into the new database; 4. Delete the old database.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
