C#实现文件读写到SQLite数据库

2025-01-09 04:50

本文主要是介绍C#实现文件读写到SQLite数据库,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《C#实现文件读写到SQLite数据库》这篇文章主要为大家详细介绍了使用C#将文件读写到SQLite数据库的几种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以参考一下...

《文件读写到SQLite数据库China编程的方法》博客中,介绍了文件读写到SQLite数据库的方法,例子使用的python语言,本文是使用 C# 将文件读写到 SQLite 数据库的几种方法的具体示例,如果有些概念模糊可参考作者以前博客。

1. 使用 BLOB 存储文件

示例代码:

using System;
using System.Data.SQLite;
using System.IO;
 
class Program
{
    static void Main(string[] args)
    {
        string databasePath = "example.db";
        string connectionString = $"Data Source={databGMCMWEYGasePath};Version=3;";
 
        // 创建数据库和表
        using (var connection = new SQLiteConnection(connectionString))
        {
            connection.Open();
            string createTableQuery = @"
                CREATE TABLE IF NOT EXISTS Files (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    data BLOB NOT NULL
                );";
            using (var command = new SQLiteCommand(createTableQuery, connection))
            {
                command.ExecuteNonQuery();
            }
        }
 
        // 插入文件到数据库
        string filePath = "example.pdf"; // 替换为你的文件路径
        InsertFile(filePath, connectionString);
 
        // 从数据库读取文件
        ReadFile(1, connectionString); // 假设读取 ID 为 1 的文件
    }
 
    static void InsertFile(string filePath, string connectionString)
    {
        byte[] fileData = File.ReadAllBytes(filePath);
        string fileName = Path.GetFileName(filePath);
 
        using (var connection = new SQLiteConnection(connectionString))
        {
            connection.Open();
            string insertQuery = "INSERT INTO Files (name, data) VALUES (@name, @data)";
            using (var command = new SQLiteCommand(insertQuery, connection))
            {
                command.Parameters.AddwithValue("@name", fileName);
                command.Parameters.AddWithValue("@data", fileData);
                command.ExecuteNonQuery();
            }
        }
 
        Console.WriteLine($"File '{fileName}' has been saved to the database.");
    }
 
    static void ReadFile(int fileId, string connectionString)
    {
        using (var connection = new SQLiteConnection(connectionString))
        {
            connection.Open();
            string selectQuery = "SELECT name, data FROM Files WHERE id = @id";
            using (var command = new SQLiteCommand(selectQuery, connection))
            {
                command.Parameters.AddWithValue("@id", fileId);
                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        string fileName = reader.GetString(0);
                        byte[] fileData = (byte[])reader["data"];
 
                        File.WriteAllBytes(fileName, fileData);
                        Console.WriteLine($"File '{fileName}' has been restored from the database.");
                    }
                }
            }
        }
    }
}

2. 存储文件路径

示例代码:

using System;
using System.Data.SQLite;
 
class Program
{
    static void Main(string[] args)
    {
        string databasePath = "example.db";
        string connectionString = $"Data Source={databasePath};Version=3;";
 
        // 创建数据库和表
        using (var connection = new SQLiteConnection(connectionString))
        {
            connection.Open();
            string createTableQuejavascriptry = @"
                CREATE TABLE IF NOT EXISTS FilePaths (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    path TEXT NOT NULL
                );";
            using (var command = new SQLiteCommand(createTableQuery, connection))
            {
                command.ExecuteNonQuery();
            }
        }
 
        // 插入文件路径
        string filePath = "example.pdf"; // 替换为你的文件路径
        InsertFilePath(filePath, connectionString);
 
        // 从数据库读取文件路径
        GetFilePath(1, connectionString); // 假设读取 ID 为 1 的文件路径
    }
 
    static void InsertFilePath(string filePath, string connectionString)
    {
        string fileName = System.IO.Path.GetFileName(filePath);
 
        using (var connection = new SQLiteConnection(connectionString))
        {
            connection.Open();
            string insertQuery = "INSERT INTO FilePaths (name, path) VALUES (@name, @path)";
            using (var command = new SQLiteCommand(insertQuery, connection))
            {
                command.Parameters.AddWithValue("@name", fileName);
                command.Parameters.AddWithValue("@path", filePath);
                command.ExecuteNonQuery()China编程;
            }
        }
 
        Console.WriteLine($"File path '{filePath}' has been saved to the database.");
    }
 
    static void GetFilePath(int fileId, string connectionString)
    {
        using (var connection = new SQLiteConnection(connectionString))
        {
            connection.Open();
            string selectQuery = "SELECT name, path FROM FilePaths WHERE id = @id";
            using (var command = new SQLiteCommand(selectQuery, connection))
            {
                command.Parameters.AddWithValue("@id", fileId);
                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        string fileName = reader.GetString(0);
                        string filePath = reader.GetString(1);
 
                        Console.WriteLine($"File '{fileName}' is located at '{filePath}'.");
                    }
                }
            }
        }
    }
}

3. 分块存储文件

示例代码:

using System;
using System.Data.SQLite;
using System.IO;
 
class Program
{
    static void Main(string[] args)
    {
        string databasePath = "example.db";
        string connectionString = $"Data Source={databasePath};Version=3;";
 
        // 创建数据库和表
        using (var connection = new SQLiteConnection(connectionString))
        {
            connection.Open();
            string createTableQuery = @"
                CREATE TABLE IF NOT EXISTS FileChunks (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    file_id INTEGER NOT NULL,
                    chunk_index INTEGER NOT NULL,
                    chunk_data BLOB NOT NULL
                );";
            using (var command = new SQLiteCommand(createTableQuery, connection))
            {
                command.ExecuteNonQuery();
            }
        }
 
        // 插入文件分块
        string filePatGMCMWEYGh = "example.pdf"; // 替换为你的文件路径
        InsertFileChunks(filePath, 1, connectionString); // 假设文件 ID 为 1
 
        // 重新组装文件
        ReassembleFile(1, "output.pdf", connectionString); // 输出为 output.pdf
    }
 
    static void InsertFileChunks(string filePath, int fileId, string connectionString)
    {
        int chunkSize = 1024 * 1024; // 每块大小为 1MB
        byte[] buffer = new byte[chunkSize];
        int chunkIndex = 0;
 
        using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        using (var connection = new SQLiteConnection(connectionString))
        {
            connection.Open();
            string insertQuery = "INSERT INTO FileChunks (file_id, chunk_index, chunk_data) VALUES (@file_id, @chunk_index, @chunk_data)";
            using (var command = new SQLiteCommand(insertQuery, connection))
            {
                int bytesRead;
                while ((bytesRead = fileStream.Read(buffer, 0, chunkSize)) > 0)
                {
                    byte[] chunkData = new byte[bytesRead];
                    Array.Copy(buffer, chunkData, bytesRead);
 
                    command.Parameters.Clear();
                    command.Parameters.AddWithValue("@file_id", fileId);
                    command.Parameters.AddWithValue("@chunk_index", chunkIndex++);
                    command.Parameters.AddWithValue("@chunk_data", chunkData);
                    command.ExecuteNonQuery();
                }
            }
        }
 
        Console.WriteLine($"File '{filePath}' has been stored in chunks.");
    }
 
    static void ReassembleFile(int fileId, string outputPath, string connectionString)
    {
        using (var connection = new SQLiteConnection(connectionString))
        {
            connection.Open();
            string selectQuery = "SELECT chunk_data FROM FileChunks WHERE file_id = @file_id ORDER BY chunk_index";
            using (var command = new SQLiteCommand(selectQuery, connection))
            {
                command.Parameters.AddWithValue("@file_id", fileId);
                using (var reader = command.ExecuteReader())
                using (var outputFile = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
                {
                    while (reader.Read())
                    {
                        byte[] chunkData = (byte[])reader["chunk_data"];
                        outputFile.Write(chunkData, 0, chunkData.Length);
                    }
                }
            }
        }
 
        Console.WriteLine($"File has been reassembled to '{outputPath}'.");
    }
}

以上就是C#实现文件读写到SQLite数据库的详细内容,更多关于C#文件读写到数据库的资料请关注编程China编程(www.chinasem.cn)其它相关文章!

这篇关于C#实现文件读写到SQLite数据库的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1152995

相关文章

通过C#获取PDF中指定文本或所有文本的字体信息

《通过C#获取PDF中指定文本或所有文本的字体信息》在设计和出版行业中,字体的选择和使用对最终作品的质量有着重要影响,然而,有时我们可能会遇到包含未知字体的PDF文件,这使得我们无法准确地复制或修改文... 目录引言C# 获取PDF中指定文本的字体信息C# 获取PDF文档中用到的所有字体信息引言在设计和出

SpringBoot项目启动后自动加载系统配置的多种实现方式

《SpringBoot项目启动后自动加载系统配置的多种实现方式》:本文主要介绍SpringBoot项目启动后自动加载系统配置的多种实现方式,并通过代码示例讲解的非常详细,对大家的学习或工作有一定的... 目录1. 使用 CommandLineRunner实现方式:2. 使用 ApplicationRunne

Python实现阶乘的四种写法

《Python实现阶乘的四种写法》本文主要介绍了Python实现阶乘的六种写法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录第一种:推导式+循环遍历列表内每个元素相乘第二种:调用functools模块reduce的php累计

Python中的可视化设计与UI界面实现

《Python中的可视化设计与UI界面实现》本文介绍了如何使用Python创建用户界面(UI),包括使用Tkinter、PyQt、Kivy等库进行基本窗口、动态图表和动画效果的实现,通过示例代码,展示... 目录从像素到界面:python带你玩转UI设计示例:使用Tkinter创建一个简单的窗口绘图魔法:用

Python实现NLP的完整流程介绍

《Python实现NLP的完整流程介绍》这篇文章主要为大家详细介绍了Python实现NLP的完整流程,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 编程安装和导入必要的库2. 文本数据准备3. 文本预处理3.1 小写化3.2 分词(Tokenizatio

Python中实现进度条的多种方法总结

《Python中实现进度条的多种方法总结》在Python编程中,进度条是一个非常有用的功能,它能让用户直观地了解任务的进度,提升用户体验,本文将介绍几种在Python中实现进度条的常用方法,并通过代码... 目录一、简单的打印方式二、使用tqdm库三、使用alive-progress库四、使用progres

基于Qt Qml实现时间轴组件

《基于QtQml实现时间轴组件》时间轴组件是现代用户界面中常见的元素,用于按时间顺序展示事件,本文主要为大家详细介绍了如何使用Qml实现一个简单的时间轴组件,需要的可以参考下... 目录写在前面效果图组件概述实现细节1. 组件结构2. 属性定义3. 数据模型4. 事件项的添加和排序5. 事件项的渲染如何使用

基于Java实现模板填充Word

《基于Java实现模板填充Word》这篇文章主要为大家详细介绍了如何用Java实现按产品经理提供的Word模板填充数据,并以word或pdf形式导出,有需要的小伙伴可以参考一下... Java实现按模板填充wor编程d本文讲解的需求是:我们需要把数据库中的某些数据按照 产品经理提供的 word模板,把数据

Python视频剪辑合并操作的实现示例

《Python视频剪辑合并操作的实现示例》很多人在创作视频时都需要进行剪辑,本文主要介绍了Python视频剪辑合并操作的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习... 目录介绍安装FFmpegWindowsMACOS安装MoviePy剪切视频合并视频转换视频结论介绍

spring6+JDK17实现SSM起步配置文件

《spring6+JDK17实现SSM起步配置文件》本文介绍了使用Spring6和JDK17配置SSM(Spring+SpringMVC+MyBatis)框架,文中通过示例代码介绍的非常详细,对大家的... 目录1.配置POM文件2.在resource目录下新建beans.XML文件,用于配置spirng3