.NET : 如何将大文件写入到数据库中
最近利用空闲时间自己在写一个文件备份工具,因为我磁盘上的很多文件很重要,例如很多PPT和讲义。所以需要经常备份,而且因为这些文件很多,所以需要增量备份。 我尝试用过windows自带的ntbackup工具,但感觉不是很爽。它不支持压缩备份,而且界面也有点复杂
最近利用空闲时间自己在写一个文件备份工具,因为我磁盘上的很多文件很重要,例如很多PPT和讲义。所以需要经常备份,而且因为这些文件很多,美国空间,所以需要增量备份。
我尝试用过windows自带的ntbackup工具,但感觉不是很爽。它不支持压缩备份,而且界面也有点复杂。
为了响应伟大领袖的“自力更生,丰衣足食”的号召,咱决定自己写一个工具,专门备份到数据库。支持压缩,支持加密,支持增量。
本文分享一下其中一些重点的技术细节
其中一个关键的技术就是将文件使用二进制的方式存放在数据库的varbinary(max)的字段中。该字段最大允许的长度为2GB。
对于一些小文件,我们可以一次性读取它的所有字节,香港虚拟主机,然后一次提交到数据库
///
/// 这个方法演示了如何一次提交所有的字节。这样导致的结果是:应用程序立即需要申请等同于文件大小的内存
///
static void SubmitFileByOnce() {
string file = @"F:\功夫熊猫.rmvb";//文件大小为519MB
byte[] buffer = File.ReadAllBytes(file);
using (SqlConnection conn = new SqlConnection("server=(local);database=demo;integrated security=true")) {
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO Files(FileName,FileContents) VALUES(@fileName,@fileContents)";
cmd.Parameters.AddRange(
new[]
{
new SqlParameter("@fileName",file),
new SqlParameter("@fileContents",buffer)
});
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
但是,上面的方法有几个问题,主要体现在如果文件比较大的话
1. 它需要一次性很大的内存,具体数据等同于文件大小。因为File.ReadAllBytes方法是将所有字节全部读入到内存。
2. 它会导致提交失败,就是因为数据太大了。数据库也会拒绝。
那么,我就对这个方法做了一下改进,将文件拆分为5MB一段,也就是说,此时每次申请的内存只有5MB。这就大大地提高了可用性。
///
/// 这个方法是将文件切分为5MB的块,每次只是提交5MB,所以可能多次提交,但内存占用就比较小
///
static void SubmitFileStepByStep() {
string file = @"F:\功夫熊猫.rmvb";//以这个文件为例,大小为519MB,香港服务器,一共需要的时间大约94秒。还是有点慢的,所以还可能需要进行压缩
FileStream fs = new FileStream(file, FileMode.Open);
byte[] buffer = new byte[5 * 1024 * 1024];
int readCount;
using (SqlConnection conn = new SqlConnection("server=(local);database=demo;integrated security=true"))
{
conn.Open();
while ((readCount = fs.Read(buffer, 0, buffer.Length)) > 0)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO Files(FileName,FileContents) VALUES(@fileName,@fileContents)";
cmd.Parameters.AddRange(
new[]
{
new SqlParameter("@fileName",file),
new SqlParameter("@fileContents",buffer)
});
cmd.ExecuteNonQuery();
}
}
conn.Close();
}
}
这样的话,有一个后果就是一个文件,可能在数据库中会有多条记录。所以在读取的时候,我们需要对其进行合并

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

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











Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

To avoid PHP database connection errors, follow best practices: check for connection errors and match variable names with credentials. Use secure storage or environment variables to avoid hardcoding credentials. Close the connection after use to prevent SQL injection and use prepared statements or bound parameters.

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.
