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

相关文章

Idea实现接口的方法上无法添加@Override注解的解决方案

《Idea实现接口的方法上无法添加@Override注解的解决方案》文章介绍了在IDEA中实现接口方法时无法添加@Override注解的问题及其解决方法,主要步骤包括更改项目结构中的Languagel... 目录Idea实现接China编程口的方法上无法添加@javascriptOverride注解错误原因解决方

使用Navicat工具比对两个数据库所有表结构的差异案例详解

《使用Navicat工具比对两个数据库所有表结构的差异案例详解》:本文主要介绍如何使用Navicat工具对比两个数据库test_old和test_new,并生成相应的DDLSQL语句,以便将te... 目录概要案例一、如图两个数据库test_old和test_new进行比较:二、开始比较总结概要公司存在多

轻松上手MYSQL之JSON函数实现高效数据查询与操作

《轻松上手MYSQL之JSON函数实现高效数据查询与操作》:本文主要介绍轻松上手MYSQL之JSON函数实现高效数据查询与操作的相关资料,MySQL提供了多个JSON函数,用于处理和查询JSON数... 目录一、jsON_EXTRACT 提取指定数据二、JSON_UNQUOTE 取消双引号三、JSON_KE

MySql死锁怎么排查的方法实现

《MySql死锁怎么排查的方法实现》本文主要介绍了MySql死锁怎么排查的方法实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录前言一、死锁排查方法1. 查看死锁日志方法 1:启用死锁日志输出方法 2:检查 mysql 错误

MySQL数据库函数之JSON_EXTRACT示例代码

《MySQL数据库函数之JSON_EXTRACT示例代码》:本文主要介绍MySQL数据库函数之JSON_EXTRACT的相关资料,JSON_EXTRACT()函数用于从JSON文档中提取值,支持对... 目录前言基本语法路径表达式示例示例 1: 提取简单值示例 2: 提取嵌套值示例 3: 提取数组中的值注意

CSS3中使用flex和grid实现等高元素布局的示例代码

《CSS3中使用flex和grid实现等高元素布局的示例代码》:本文主要介绍了使用CSS3中的Flexbox和Grid布局实现等高元素布局的方法,通过简单的两列实现、每行放置3列以及全部代码的展示,展示了这两种布局方式的实现细节和效果,详细内容请阅读本文,希望能对你有所帮助... 过往的实现方法是使用浮动加

Go Mongox轻松实现MongoDB的时间字段自动填充

《GoMongox轻松实现MongoDB的时间字段自动填充》这篇文章主要为大家详细介绍了Go语言如何使用mongox库,在插入和更新数据时自动填充时间字段,从而提升开发效率并减少重复代码,需要的可以... 目录前言时间字段填充规则Mongox 的安装使用 Mongox 进行插入操作使用 Mongox 进行更

MySQL修改密码的四种实现方式

《MySQL修改密码的四种实现方式》文章主要介绍了如何使用命令行工具修改MySQL密码,包括使用`setpassword`命令和`mysqladmin`命令,此外,还详细描述了忘记密码时的处理方法,包... 目录mysql修改密码四种方式一、set password命令二、使用mysqladmin三、修改u

Java实现状态模式的示例代码

《Java实现状态模式的示例代码》状态模式是一种行为型设计模式,允许对象根据其内部状态改变行为,本文主要介绍了Java实现状态模式的示例代码,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来... 目录一、简介1、定义2、状态模式的结构二、Java实现案例1、电灯开关状态案例2、番茄工作法状态案例

一文教你使用Python实现本地分页

《一文教你使用Python实现本地分页》这篇文章主要为大家详细介绍了Python如何实现本地分页的算法,主要针对二级数据结构,文中的示例代码简洁易懂,有需要的小伙伴可以了解下... 在项目开发的过程中,遇到分页的第一页就展示大量的数据,导致前端列表加载展示的速度慢,所以需要在本地加入分页处理,把所有数据先放