当前位置: 代码网 > it编程>编程语言>Asp.net > C# SQLite 高级功能详解(推荐)

C# SQLite 高级功能详解(推荐)

2025年06月17日 Asp.net 我要评论
sqlite 基础介绍sqlite 是一个轻量级的嵌入式关系数据库,特别适合桌面应用程序和移动应用程序。它支持 acid 特性,提供了强大的事务控制功能。主要特点无需服务器配置跨平台支持支持标准 sq

sqlite 基础介绍

sqlite 是一个轻量级的嵌入式关系数据库,特别适合桌面应用程序和移动应用程序。它支持 acid 特性,提供了强大的事务控制功能。

主要特点

  • 无需服务器配置
  • 跨平台支持
  • 支持标准 sql 语法
  • 文件级数据库
  • 支持事务和 acid 特性

环境配置

首先安装必要的 nuget 包:

<packagereference include="microsoft.data.sqlite" version="7.0.0" />
<packagereference include="system.data.sqlite" version="1.0.118" />

基础连接设置:

using microsoft.data.sqlite;
using system.data;
using system.data.sqlite;
public class databaseconnection
{
    private readonly string _connectionstring;
    public databaseconnection(string databasepath)
    {
        _connectionstring = $"data source={databasepath};";
    }
    public sqliteconnection getconnection()
    {
        return new sqliteconnection(_connectionstring);
    }
}

事务处理详解

事务基础概念

事务是数据库操作的基本单元,必须满足 acid 特性:

  • 原子性(atomicity):事务中的所有操作要么全部完成,要么全部不执行
  • 一致性(consistency):事务前后数据库状态保持一致
  • 隔离性(isolation):并发事务之间相互隔离
  • 持久性(durability):事务提交后,数据永久保存

基本事务操作

public class transactionexample
{
    private readonly string _connectionstring;
    public transactionexample(string connectionstring)
    {
        _connectionstring = connectionstring;
    }
    // 基本事务操作
    public void basictransactionexample()
    {
        using var connection = new sqliteconnection(_connectionstring);
        connection.open();
        using var transaction = connection.begintransaction();
        try
        {
            // 创建命令并关联事务
            using var command = connection.createcommand();
            command.transaction = transaction;
            // 执行多个相关操作
            command.commandtext = "insert into users (name, email) values (@name, @email)";
            command.parameters.addwithvalue("@name", "张三");
            command.parameters.addwithvalue("@email", "zhangsan@example.com");
            command.executenonquery();
            command.parameters.clear();
            command.commandtext = "insert into userprofiles (userid, age) values (last_insert_rowid(), @age)";
            command.parameters.addwithvalue("@age", 25);
            command.executenonquery();
            // 提交事务
            transaction.commit();
            console.writeline("事务成功提交");
        }
        catch (exception ex)
        {
            // 回滚事务
            transaction.rollback();
            console.writeline($"事务回滚: {ex.message}");
            throw;
        }
    }
}

高级事务控制

public class advancedtransactioncontrol
{
    private readonly string _connectionstring;
    public advancedtransactioncontrol(string connectionstring)
    {
        _connectionstring = connectionstring;
    }
    // 设置事务隔离级别
    public void transactionwithisolationlevel()
    {
        using var connection = new sqliteconnection(_connectionstring);
        connection.open();
        // sqlite 支持的隔离级别
        using var transaction = connection.begintransaction(isolationlevel.serializable);
        try
        {
            var command = connection.createcommand();
            command.transaction = transaction;
            // 执行业务逻辑
            command.commandtext = "update accounts set balance = balance - 100 where id = 1";
            int affected = command.executenonquery();
            if (affected == 0)
            {
                throw new invalidoperationexception("账户不存在或余额不足");
            }
            command.commandtext = "update accounts set balance = balance + 100 where id = 2";
            command.executenonquery();
            transaction.commit();
        }
        catch
        {
            transaction.rollback();
            throw;
        }
    }
    // 嵌套事务(保存点)
    public void savepointexample()
    {
        using var connection = new sqliteconnection(_connectionstring);
        connection.open();
        using var maintransaction = connection.begintransaction();
        try
        {
            var command = connection.createcommand();
            command.transaction = maintransaction;
            // 主要操作
            command.commandtext = "insert into orders (customerid, amount) values (1, 100)";
            command.executenonquery();
            // 创建保存点
            command.commandtext = "savepoint sp1";
            command.executenonquery();
            try
            {
                // 可能失败的操作
                command.commandtext = "insert into orderdetails (orderid, productid) values (last_insert_rowid(), 999)";
                command.executenonquery();
            }
            catch
            {
                // 回滚到保存点
                command.commandtext = "rollback to sp1";
                command.executenonquery();
                // 执行替代操作
                command.commandtext = "insert into orderdetails (orderid, productid) values (last_insert_rowid(), 1)";
                command.executenonquery();
            }
            // 释放保存点
            command.commandtext = "release sp1";
            command.executenonquery();
            maintransaction.commit();
        }
        catch
        {
            maintransaction.rollback();
            throw;
        }
    }
}

事务性业务逻辑封装

public class bankingservice
{
    private readonly string _connectionstring;
    public bankingservice(string connectionstring)
    {
        _connectionstring = connectionstring;
    }
    // 转账操作 - 事务应用实例
    public async task<bool> transfermoney(int fromaccountid, int toaccountid, decimal amount)
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        using var transaction = await connection.begintransactionasync();
        try
        {
            // 检查源账户余额
            decimal sourcebalance = await getaccountbalance(connection, transaction, fromaccountid);
            if (sourcebalance < amount)
            {
                throw new invalidoperationexception("余额不足");
            }
            // 从源账户扣款
            await updateaccountbalance(connection, transaction, fromaccountid, -amount);
            // 向目标账户加款
            await updateaccountbalance(connection, transaction, toaccountid, amount);
            // 记录转账历史
            await recordtransferhistory(connection, transaction, fromaccountid, toaccountid, amount);
            await transaction.commitasync();
            return true;
        }
        catch (exception ex)
        {
            await transaction.rollbackasync();
            console.writeline($"转账失败: {ex.message}");
            return false;
        }
    }
    private async task<decimal> getaccountbalance(sqliteconnection connection, sqlitetransaction transaction, int accountid)
    {
        using var command = connection.createcommand();
        command.transaction = transaction;
        command.commandtext = "select balance from accounts where id = @id for update"; // 行锁定
        command.parameters.addwithvalue("@id", accountid);
        var result = await command.executescalarasync();
        return result != null ? convert.todecimal(result) : 0;
    }
    private async task updateaccountbalance(sqliteconnection connection, sqlitetransaction transaction, int accountid, decimal amount)
    {
        using var command = connection.createcommand();
        command.transaction = transaction;
        command.commandtext = "update accounts set balance = balance + @amount where id = @id";
        command.parameters.addwithvalue("@amount", amount);
        command.parameters.addwithvalue("@id", accountid);
        int affected = await command.executenonqueryasync();
        if (affected == 0)
        {
            throw new invalidoperationexception($"账户 {accountid} 不存在");
        }
    }
    private async task recordtransferhistory(sqliteconnection connection, sqlitetransaction transaction, 
        int fromaccountid, int toaccountid, decimal amount)
    {
        using var command = connection.createcommand();
        command.transaction = transaction;
        command.commandtext = @"
            insert into transferhistory (fromaccountid, toaccountid, amount, transferdate) 
            values (@from, @to, @amount, @date)";
        command.parameters.addwithvalue("@from", fromaccountid);
        command.parameters.addwithvalue("@to", toaccountid);
        command.parameters.addwithvalue("@amount", amount);
        command.parameters.addwithvalue("@date", datetime.utcnow);
        await command.executenonqueryasync();
    }
}

连接管理与连接池

sqlite 连接管理和池化:

public class connectionpoolmanager
{
    private readonly concurrentqueue<sqliteconnection> _connectionpool;
    private readonly string _connectionstring;
    private readonly int _maxpoolsize;
    private int _currentpoolsize;
    public connectionpoolmanager(string connectionstring, int maxpoolsize = 10)
    {
        _connectionstring = connectionstring;
        _maxpoolsize = maxpoolsize;
        _connectionpool = new concurrentqueue<sqliteconnection>();
        _currentpoolsize = 0;
    }
    public async task<sqliteconnection> getconnectionasync()
    {
        if (_connectionpool.trydequeue(out var connection))
        {
            if (connection.state == connectionstate.open)
            {
                return connection;
            }
            else
            {
                connection.dispose();
                interlocked.decrement(ref _currentpoolsize);
            }
        }
        // 创建新连接
        connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        interlocked.increment(ref _currentpoolsize);
        return connection;
    }
    public void returnconnection(sqliteconnection connection)
    {
        if (connection.state == connectionstate.open && _currentpoolsize <= _maxpoolsize)
        {
            _connectionpool.enqueue(connection);
        }
        else
        {
            connection.dispose();
            interlocked.decrement(ref _currentpoolsize);
        }
    }
    public void dispose()
    {
        while (_connectionpool.trydequeue(out var connection))
        {
            connection.dispose();
        }
    }
}

批量操作优化

public class batchoperations
{
    private readonly string _connectionstring;
    public batchoperations(string connectionstring)
    {
        _connectionstring = connectionstring;
    }
    // 批量插入优化
    public async task bulkinsertoptimized(list<user> users)
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        using var transaction = await connection.begintransactionasync();
        try
        {
            // 方法1:使用参数化批量插入
            using var command = connection.createcommand();
            command.transaction = transaction;
            command.commandtext = "insert into users (name, email, age) values (@name, @email, @age)";
            var nameparam = command.parameters.add("@name", sqlitetype.text);
            var emailparam = command.parameters.add("@email", sqlitetype.text);
            var ageparam = command.parameters.add("@age", sqlitetype.integer);
            foreach (var user in users)
            {
                nameparam.value = user.name;
                emailparam.value = user.email;
                ageparam.value = user.age;
                await command.executenonqueryasync();
            }
            await transaction.commitasync();
        }
        catch
        {
            await transaction.rollbackasync();
            throw;
        }
    }
    // 超大批量插入(分批处理)
    public async task bulkinsertlargedataset(ienumerable<user> users, int batchsize = 1000)
    {
        var userlist = users.tolist();
        int totalbatches = (int)math.ceiling((double)userlist.count / batchsize);
        for (int batch = 0; batch < totalbatches; batch++)
        {
            var batchusers = userlist.skip(batch * batchsize).take(batchsize);
            await bulkinsertoptimized(batchusers.tolist());
            // 可选:报告进度
            console.writeline($"处理批次 {batch + 1}/{totalbatches}");
        }
    }
    // 使用 values 子句批量插入
    public async task bulkinsertwithvalues(list<user> users)
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        using var transaction = await connection.begintransactionasync();
        try
        {
            const int batchsize = 500;
            for (int i = 0; i < users.count; i += batchsize)
            {
                var batch = users.skip(i).take(batchsize);
                var values = new list<string>();
                var parameters = new list<sqliteparameter>();
                int paramindex = 0;
                foreach (var user in batch)
                {
                    values.add($"(@name{paramindex}, @email{paramindex}, @age{paramindex})");
                    parameters.add(new sqliteparameter($"@name{paramindex}", user.name));
                    parameters.add(new sqliteparameter($"@email{paramindex}", user.email));
                    parameters.add(new sqliteparameter($"@age{paramindex}", user.age));
                    paramindex++;
                }
                using var command = connection.createcommand();
                command.transaction = transaction;
                command.commandtext = $"insert into users (name, email, age) values {string.join(", ", values)}";
                command.parameters.addrange(parameters.toarray());
                await command.executenonqueryasync();
            }
            await transaction.commitasync();
        }
        catch
        {
            await transaction.rollbackasync();
            throw;
        }
    }
}

异步操作

public class asyncdatabaseoperations
{
    private readonly string _connectionstring;
    public asyncdatabaseoperations(string connectionstring)
    {
        _connectionstring = connectionstring;
    }
    // 异步事务操作
    public async task<bool> processorderasync(order order, list<orderitem> items)
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        using var transaction = await connection.begintransactionasync();
        try
        {
            // 插入订单
            long orderid = await insertorderasync(connection, transaction, order);
            // 并行处理订单项
            var tasks = items.select(item => insertorderitemasync(connection, transaction, orderid, item));
            await task.whenall(tasks);
            // 更新库存
            await updateinventoryasync(connection, transaction, items);
            await transaction.commitasync();
            return true;
        }
        catch (exception ex)
        {
            await transaction.rollbackasync();
            console.writeline($"订单处理失败: {ex.message}");
            return false;
        }
    }
    private async task<long> insertorderasync(sqliteconnection connection, sqlitetransaction transaction, order order)
    {
        using var command = connection.createcommand();
        command.transaction = transaction;
        command.commandtext = @"
            insert into orders (customerid, orderdate, totalamount) 
            values (@customerid, @orderdate, @totalamount);
            select last_insert_rowid();";
        command.parameters.addwithvalue("@customerid", order.customerid);
        command.parameters.addwithvalue("@orderdate", order.orderdate);
        command.parameters.addwithvalue("@totalamount", order.totalamount);
        var result = await command.executescalarasync();
        return convert.toint64(result);
    }
    private async task insertorderitemasync(sqliteconnection connection, sqlitetransaction transaction, 
        long orderid, orderitem item)
    {
        using var command = connection.createcommand();
        command.transaction = transaction;
        command.commandtext = @"
            insert into orderitems (orderid, productid, quantity, unitprice) 
            values (@orderid, @productid, @quantity, @unitprice)";
        command.parameters.addwithvalue("@orderid", orderid);
        command.parameters.addwithvalue("@productid", item.productid);
        command.parameters.addwithvalue("@quantity", item.quantity);
        command.parameters.addwithvalue("@unitprice", item.unitprice);
        await command.executenonqueryasync();
    }
    private async task updateinventoryasync(sqliteconnection connection, sqlitetransaction transaction, 
        list<orderitem> items)
    {
        using var command = connection.createcommand();
        command.transaction = transaction;
        foreach (var item in items)
        {
            command.commandtext = "update products set stock = stock - @quantity where id = @productid";
            command.parameters.clear();
            command.parameters.addwithvalue("@quantity", item.quantity);
            command.parameters.addwithvalue("@productid", item.productid);
            int affected = await command.executenonqueryasync();
            if (affected == 0)
            {
                throw new invalidoperationexception($"产品 {item.productid} 库存更新失败");
            }
        }
    }
}

索引优化

public class indexoptimization
{
    private readonly string _connectionstring;
    public indexoptimization(string connectionstring)
    {
        _connectionstring = connectionstring;
    }
    // 创建和管理索引
    public async task createoptimalindexes()
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        using var command = connection.createcommand();
        // 单列索引
        command.commandtext = "create index if not exists idx_users_email on users(email)";
        await command.executenonqueryasync();
        // 复合索引
        command.commandtext = "create index if not exists idx_orders_customer_date on orders(customerid, orderdate)";
        await command.executenonqueryasync();
        // 部分索引(条件索引)
        command.commandtext = "create index if not exists idx_orders_pending on orders(orderdate) where status = 'pending'";
        await command.executenonqueryasync();
        // 唯一索引
        command.commandtext = "create unique index if not exists idx_users_username on users(username)";
        await command.executenonqueryasync();
    }
    // 分析查询性能
    public async task analyzequeryperformance(string query)
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        using var command = connection.createcommand();
        command.commandtext = $"explain query plan {query}";
        using var reader = await command.executereaderasync();
        console.writeline("查询执行计划:");
        while (await reader.readasync())
        {
            console.writeline($"id: {reader[0]}, parent: {reader[1]}, notused: {reader[2]}, detail: {reader[3]}");
        }
    }
    // 索引使用统计
    public async task getindexstatistics()
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        using var command = connection.createcommand();
        command.commandtext = @"
            select name, sql 
            from sqlite_master 
            where type = 'index' 
            and sql is not null
            order by name";
        using var reader = await command.executereaderasync();
        console.writeline("数据库索引列表:");
        while (await reader.readasync())
        {
            console.writeline($"索引: {reader["name"]}, sql: {reader["sql"]}");
        }
    }
}

锁机制与并发控制

public class concurrencycontrol
{
    private readonly string _connectionstring;
    private readonly semaphoreslim _semaphore;
    public concurrencycontrol(string connectionstring, int maxconcurrentconnections = 5)
    {
        _connectionstring = connectionstring;
        _semaphore = new semaphoreslim(maxconcurrentconnections, maxconcurrentconnections);
    }
    // 悲观锁实现
    public async task<bool> updatewithpessimisticlock(int userid, string newemail)
    {
        await _semaphore.waitasync();
        try
        {
            using var connection = new sqliteconnection(_connectionstring);
            await connection.openasync();
            using var transaction = await connection.begintransactionasync(isolationlevel.serializable);
            try
            {
                // 查询并锁定行
                using var selectcommand = connection.createcommand();
                selectcommand.transaction = transaction;
                selectcommand.commandtext = "select email, version from users where id = @id";
                selectcommand.parameters.addwithvalue("@id", userid);
                using var reader = await selectcommand.executereaderasync();
                if (!await reader.readasync())
                {
                    return false;
                }
                string currentemail = reader["email"].tostring();
                int currentversion = convert.toint32(reader["version"]);
                reader.close();
                // 模拟业务处理时间
                await task.delay(100);
                // 更新数据
                using var updatecommand = connection.createcommand();
                updatecommand.transaction = transaction;
                updatecommand.commandtext = @"
                    update users 
                    set email = @email, version = version + 1, updatedat = @updatedat
                    where id = @id and version = @version";
                updatecommand.parameters.addwithvalue("@email", newemail);
                updatecommand.parameters.addwithvalue("@updatedat", datetime.utcnow);
                updatecommand.parameters.addwithvalue("@id", userid);
                updatecommand.parameters.addwithvalue("@version", currentversion);
                int affected = await updatecommand.executenonqueryasync();
                if (affected > 0)
                {
                    await transaction.commitasync();
                    return true;
                }
                else
                {
                    await transaction.rollbackasync();
                    return false;
                }
            }
            catch
            {
                await transaction.rollbackasync();
                throw;
            }
        }
        finally
        {
            _semaphore.release();
        }
    }
    // 乐观锁实现
    public async task<bool> updatewithoptimisticlock(int userid, string newemail, int expectedversion)
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        using var command = connection.createcommand();
        command.commandtext = @"
            update users 
            set email = @email, version = version + 1, updatedat = @updatedat
            where id = @id and version = @expectedversion";
        command.parameters.addwithvalue("@email", newemail);
        command.parameters.addwithvalue("@updatedat", datetime.utcnow);
        command.parameters.addwithvalue("@id", userid);
        command.parameters.addwithvalue("@expectedversion", expectedversion);
        int affected = await command.executenonqueryasync();
        return affected > 0;
    }
    // 分布式锁模拟
    public async task<bool> tryacquiredistributedlock(string lockname, timespan expiration)
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        using var command = connection.createcommand();
        command.commandtext = @"
            insert or ignore into distributedlocks (lockname, expiresat, createdat)
            values (@lockname, @expiresat, @createdat)";
        command.parameters.addwithvalue("@lockname", lockname);
        command.parameters.addwithvalue("@expiresat", datetime.utcnow.add(expiration));
        command.parameters.addwithvalue("@createdat", datetime.utcnow);
        int affected = await command.executenonqueryasync();
        return affected > 0;
    }
    public async task releaselock(string lockname)
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        using var command = connection.createcommand();
        command.commandtext = "delete from distributedlocks where lockname = @lockname";
        command.parameters.addwithvalue("@lockname", lockname);
        await command.executenonqueryasync();
    }
}

备份与恢复

public class backupandrestore
{
    private readonly string _connectionstring;
    public backupandrestore(string connectionstring)
    {
        _connectionstring = connectionstring;
    }
    // 在线备份
    public async task backupdatabase(string backuppath)
    {
        using var sourceconnection = new sqliteconnection(_connectionstring);
        using var backupconnection = new sqliteconnection($"data source={backuppath}");
        await sourceconnection.openasync();
        await backupconnection.openasync();
        // 使用 sqlite 内置备份 api
        sourceconnection.backupdatabase(backupconnection, "main", "main");
        console.writeline($"数据库备份完成: {backuppath}");
    }
    // 增量备份(通过时间戳)
    public async task incrementalbackup(string backuppath, datetime lastbackuptime)
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        // 导出自上次备份以来的更改
        var tables = new[] { "users", "orders", "orderitems" };
        var backupdata = new dictionary<string, list<dictionary<string, object>>>();
        foreach (var table in tables)
        {
            using var command = connection.createcommand();
            command.commandtext = $"select * from {table} where updatedat > @lastbackup";
            command.parameters.addwithvalue("@lastbackup", lastbackuptime);
            using var reader = await command.executereaderasync();
            var tabledata = new list<dictionary<string, object>>();
            while (await reader.readasync())
            {
                var row = new dictionary<string, object>();
                for (int i = 0; i < reader.fieldcount; i++)
                {
                    row[reader.getname(i)] = reader.getvalue(i);
                }
                tabledata.add(row);
            }
            backupdata[table] = tabledata;
        }
        // 序列化备份数据
        var json = system.text.json.jsonserializer.serialize(backupdata, new jsonserializeroptions { writeindented = true });
        await file.writealltextasync(backuppath, json);
        console.writeline($"增量备份完成: {backuppath}");
    }
    // 事务日志备份
    public async task backupwithtransactionlog(string backuppath)
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        using var transaction = await connection.begintransactionasync();
        try
        {
            // 创建备份点
            using var command = connection.createcommand();
            command.transaction = transaction;
            command.commandtext = "insert into backuplog (backuptime, backuppath, status) values (@time, @path, 'started')";
            command.parameters.addwithvalue("@time", datetime.utcnow);
            command.parameters.addwithvalue("@path", backuppath);
            await command.executenonqueryasync();
            // 执行实际备份
            await backupdatabase(backuppath);
            // 更新备份状态
            command.commandtext = "update backuplog set status = 'completed' where backuppath = @path";
            await command.executenonqueryasync();
            await transaction.commitasync();
        }
        catch
        {
            await transaction.rollbackasync();
            throw;
        }
    }
    // 验证备份完整性
    public async task<bool> validatebackup(string backuppath)
    {
        try
        {
            using var connection = new sqliteconnection($"data source={backuppath}");
            await connection.openasync();
            using var command = connection.createcommand();
            command.commandtext = "pragma integrity_check";
            var result = await command.executescalarasync();
            return result?.tostring() == "ok";
        }
        catch
        {
            return false;
        }
    }
}

性能优化技巧

public class performanceoptimization
{
    private readonly string _connectionstring;
    public performanceoptimization(string connectionstring)
    {
        _connectionstring = connectionstring;
    }
    // 数据库配置优化
    public async task optimizedatabasesettings()
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        using var command = connection.createcommand();
        // 设置 wal 模式(写前日志)
        command.commandtext = "pragma journal_mode = wal";
        await command.executenonqueryasync();
        // 设置同步模式
        command.commandtext = "pragma synchronous = normal";
        await command.executenonqueryasync();
        // 设置缓存大小(页数)
        command.commandtext = "pragma cache_size = 10000";
        await command.executenonqueryasync();
        // 设置页面大小
        command.commandtext = "pragma page_size = 4096";
        await command.executenonqueryasync();
        // 启用外键约束
        command.commandtext = "pragma foreign_keys = on";
        await command.executenonqueryasync();
        // 设置临时存储
        command.commandtext = "pragma temp_store = memory";
        await command.executenonqueryasync();
        console.writeline("数据库性能设置已优化");
    }
    // 查询优化示例
    public async task optimizedqueries()
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        // 使用参数化查询和适当的索引
        using var command = connection.createcommand();
        // 优化:使用覆盖索引
        command.commandtext = @"
            select userid, count(*) as ordercount, sum(totalamount) as totalspent
            from orders 
            where orderdate between @startdate and @enddate
            group by userid
            having count(*) > 5
            order by totalspent desc
            limit 100";
        command.parameters.addwithvalue("@startdate", datetime.now.addmonths(-3));
        command.parameters.addwithvalue("@enddate", datetime.now);
        using var reader = await command.executereaderasync();
        var results = new list<customersummary>();
        while (await reader.readasync())
        {
            results.add(new customersummary
            {
                userid = reader.getint32("userid"),
                ordercount = reader.getint32("ordercount"),
                totalspent = reader.getdecimal("totalspent")
            });
        }
    }
    // 批量数据处理优化
    public async task optimizedbatchprocessing<t>(ienumerable<t> items, func<t, sqlitecommand, task> processitem)
    {
        const int batchsize = 1000;
        const int maxconcurrency = environment.processorcount;
        var semaphore = new semaphoreslim(maxconcurrency);
        var batches = items.chunk(batchsize);
        var tasks = batches.select(async batch =>
        {
            await semaphore.waitasync();
            try
            {
                using var connection = new sqliteconnection(_connectionstring);
                await connection.openasync();
                using var transaction = await connection.begintransactionasync();
                try
                {
                    using var command = connection.createcommand();
                    command.transaction = transaction;
                    foreach (var item in batch)
                    {
                        await processitem(item, command);
                    }
                    await transaction.commitasync();
                }
                catch
                {
                    await transaction.rollbackasync();
                    throw;
                }
            }
            finally
            {
                semaphore.release();
            }
        });
        await task.whenall(tasks);
    }
    // 性能监控
    public async task monitorperformance()
    {
        using var connection = new sqliteconnection(_connectionstring);
        await connection.openasync();
        using var command = connection.createcommand();
        // 获取数据库统计信息
        var stats = new dictionary<string, object>();
        command.commandtext = "pragma page_count";
        stats["pagecount"] = await command.executescalarasync();
        command.commandtext = "pragma page_size";
        stats["pagesize"] = await command.executescalarasync();
        command.commandtext = "pragma cache_size";
        stats["cachesize"] = await command.executescalarasync();
        command.commandtext = "pragma journal_mode";
        stats["journalmode"] = await command.executescalarasync();
        console.writeline("数据库性能统计:");
        foreach (var stat in stats)
        {
            console.writeline($"{stat.key}: {stat.value}");
        }
    }
}

实体类定义

// 支持类定义
public class user
{
    public int id { get; set; }
    public string name { get; set; }
    public string email { get; set; }
    public string username { get; set; }
    public int age { get; set; }
    public int version { get; set; }
    public datetime updatedat { get; set; }
}
public class order
{
    public int id { get; set; }
    public int customerid { get; set; }
    public datetime orderdate { get; set; }
    public decimal totalamount { get; set; }
    public string status { get; set; }
}
public class orderitem
{
    public int id { get; set; }
    public int orderid { get; set; }
    public int productid { get; set; }
    public int quantity { get; set; }
    public decimal unitprice { get; set; }
}
public class customersummary
{
    public int userid { get; set; }
    public int ordercount { get; set; }
    public decimal totalspent { get; set; }
}

数据库表结构

-- 创建示例表结构
create table users (
    id integer primary key autoincrement,
    name text not null,
    email text unique not null,
    username text unique,
    age integer,
    version integer default 0,
    updatedat datetime default current_timestamp
);
create table orders (
    id integer primary key autoincrement,
    customerid integer not null,
    orderdate datetime not null,
    totalamount decimal(10,2) not null,
    status text default 'pending',
    updatedat datetime default current_timestamp,
    foreign key (customerid) references users(id)
);
create table orderitems (
    id integer primary key autoincrement,
    orderid integer not null,
    productid integer not null,
    quantity integer not null,
    unitprice decimal(10,2) not null,
    foreign key (orderid) references orders(id)
);
create table accounts (
    id integer primary key autoincrement,
    accountnumber text unique not null,
    balance decimal(15,2) not null default 0
);
create table transferhistory (
    id integer primary key autoincrement,
    fromaccountid integer not null,
    toaccountid integer not null,
    amount decimal(15,2) not null,
    transferdate datetime not null,
    foreign key (fromaccountid) references accounts(id),
    foreign key (toaccountid) references accounts(id)
);
create table distributedlocks (
    lockname text primary key,
    expiresat datetime not null,
    createdat datetime not null
);
create table backuplog (
    id integer primary key autoincrement,
    backuptime datetime not null,
    backuppath text not null,
    status text not null
);

总结

本文档详细介绍了 c# 与 sqlite 数据库的高级功能使用,重点包括:

  • 事务处理:从基本事务到嵌套事务,涵盖了各种事务控制场景
  • 连接管理:连接池化和资源优化
  • 批量操作:高效的数据批量处理方法
  • 异步编程:现代异步操作模式
  • 性能优化:索引、查询优化和系统配置
  • 并发控制:悲观锁、乐观锁和分布式锁
  • 备份恢复:数据安全和灾难恢复

到此这篇关于c# sqlite 高级功能详解的文章就介绍到这了,更多相关c# sqlite 功能内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com