Sqlx 0.5.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Sqlx --version 0.5.0
                    
NuGet\Install-Package Sqlx -Version 0.5.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Sqlx" Version="0.5.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Sqlx" Version="0.5.0" />
                    
Directory.Packages.props
<PackageReference Include="Sqlx" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Sqlx --version 0.5.0
                    
#r "nuget: Sqlx, 0.5.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Sqlx@0.5.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Sqlx&version=0.5.0
                    
Install as a Cake Addin
#tool nuget:?package=Sqlx&version=0.5.0
                    
Install as a Cake Tool

Sqlx - 高性能 .NET 数据访问库

<div align="center">

NuGet Tests Coverage License .NET

极致性能 · 类型安全 · 完全异步 · 零配置

快速开始 · 核心特性 · 性能对比 · 文档

</div>


💡 什么是 Sqlx?

Sqlx 是一个高性能、类型安全的 .NET 数据访问库,通过源代码生成器在编译时生成数据访问代码,实现接近 ADO.NET 的性能,同时提供优雅的 API 和强大的功能。

为什么选择 Sqlx?

特性 Sqlx Dapper EF Core
性能 ⚡⚡⚡⚡⚡ ⚡⚡⚡⚡ ⚡⚡⚡
内存占用 🟢 极低 🟡 低 🔴 高
类型安全 ✅ 编译时 ⚠️ 运行时 ✅ 编译时
SQL控制 ✅ 完全 ✅ 完全 ⚠️ 有限
学习曲线 📈 极低 📈 低 📈📈 中等
AOT支持 ✅ 完整 ✅ 完整 ⚠️ 有限
批量操作 ✅ 自动优化 ⚠️ 手动 ✅ 支持

⚡ 快速开始

1. 安装

dotnet add package Sqlx

2. 定义实体和仓储

// 实体
public class User
{
    public long Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

// 仓储接口和实现
[TableName("users")]
[SqlDefine(SqlDefineTypes.SQLite)]
[RepositoryFor(typeof(IUserRepository))]
public partial class UserRepository(DbConnection connection) : IUserRepository { }

public interface IUserRepository
{
    [SqlTemplate("SELECT {{columns}} FROM {{table}} WHERE id = @id")]
    Task<User?> GetByIdAsync(long id);

    [SqlTemplate("INSERT INTO {{table}} (name, age) VALUES (@name, @age)")]
    [ReturnInsertedId]
    Task<long> InsertAsync(string name, int age);
    
    [SqlTemplate("INSERT INTO {{table}} (name, age) VALUES {{batch_values}}")]
    Task<int> BatchInsertAsync(IEnumerable<User> users);
}

3. 使用

await using var conn = new SqliteConnection("Data Source=app.db");
await conn.OpenAsync();

var repo = new UserRepository(conn);

// 单条插入
var userId = await repo.InsertAsync("Alice", 25);
var user = await repo.GetByIdAsync(userId);

// 批量插入(自动优化)
var users = Enumerable.Range(1, 100).Select(i => new User 
{ 
    Name = $"User{i}", 
    Age = 20 + i 
});
await repo.BatchInsertAsync(users);

📊 性能对比

真实 Benchmark 数据

基于 BenchmarkDotNet 在 .NET 9.0 上的测试结果:

批量插入 10 行
方法 平均耗时 内存分配 相对性能
Sqlx (Batch) 118.0 μs 14.05 KB 基准
Dapper (Individual) 188.5 μs 26.78 KB 慢 60%

Sqlx 优势: 速度快 37%,内存少 48%

批量插入 100 行
方法 平均耗时 内存分配 相对性能
Sqlx (Batch) 1.351 ms 126.31 KB 基准
Dapper (Individual) 1.332 ms 251.5 KB 相当

Sqlx 优势: 速度相当,内存少 50%

性能特点

  • 编译时代码生成 - 零运行时反射开销
  • 批量操作优化 - 自动合并 SQL 语句
  • 内存高效 - 比 Dapper 节省 48-50% 内存
  • AOT 友好 - 完全支持 Native AOT

💡 测试环境: AMD Ryzen 7 5800H, .NET 9.0.8, Windows 10
📊 完整报告: 查看 tests/Sqlx.Benchmarks/ 目录


🎯 核心特性

1. 编译时代码生成

// 你写的代码
[SqlTemplate("SELECT * FROM users WHERE age >= @minAge")]
Task<List<User>> GetAdultUsersAsync(int minAge);

// 生成器自动生成高性能实现
// - 零反射
// - 零动态代码
// - 完全类型安全

2. 70+ 占位符系统

跨数据库 SQL 模板,一次编写,多处运行:

[SqlTemplate(@"
    SELECT {{columns --exclude Password}}
    FROM {{table}}
    WHERE age >= @minAge
    {{orderby created_at --desc}}
    {{limit}}
")]
Task<List<User>> QueryUsersAsync(int minAge, int? limit = null);

支持的占位符:

  • {{columns}} - 自动列名
  • {{table}} - 表名
  • {{where}} - WHERE 子句
  • {{orderby}} - ORDER BY 子句
  • {{limit}} / {{offset}} - 分页
  • {{batch_values}} - 批量插入
  • {{bool_true}} / {{bool_false}} - 布尔值
  • 还有 60+ 个占位符...

3. 多数据库支持

一套代码,4个数据库:

// 统一接口
public interface IUnifiedRepo
{
    [SqlTemplate("SELECT {{columns}} FROM {{table}} WHERE is_active = {{bool_true}}")]
    Task<List<User>> GetActiveAsync();
}

// SQLite 实现
[RepositoryFor(typeof(IUnifiedRepo), Dialect = "SQLite", TableName = "users")]
public partial class SQLiteRepo(DbConnection conn) : IUnifiedRepo { }

// PostgreSQL 实现
[RepositoryFor(typeof(IUnifiedRepo), Dialect = "PostgreSql", TableName = "users")]
public partial class PostgreSQLRepo(DbConnection conn) : IUnifiedRepo { }

// MySQL 实现
[RepositoryFor(typeof(IUnifiedRepo), Dialect = "MySql", TableName = "users")]
public partial class MySQLRepo(DbConnection conn) : IUnifiedRepo { }

// SQL Server 实现
[RepositoryFor(typeof(IUnifiedRepo), Dialect = "SqlServer", TableName = "users")]
public partial class SqlServerRepo(DbConnection conn) : IUnifiedRepo { }

4. 批量操作

自动分批处理,性能优化:

[SqlTemplate("INSERT INTO users (name, age) VALUES {{batch_values}}")]
[BatchOperation(MaxBatchSize = 500)]
Task<int> BatchInsertAsync(IEnumerable<User> users);

// 自动处理:
// - 1000 条数据 → 自动分成 2 批(500 + 500)
// - 自动事务管理
// - 内存优化

5. 表达式树查询

类型安全的动态查询:

[SqlTemplate("SELECT {{columns}} FROM {{table}} {{where}}")]
Task<List<User>> QueryAsync([ExpressionToSql] Expression<Func<User, bool>> predicate);

// 使用
var users = await repo.QueryAsync(u => u.Age >= 18 && u.Balance > 1000);
// 生成: SELECT * FROM users WHERE age >= 18 AND balance > 1000

6. SQL 调试功能

通过返回类型获取生成的 SQL,无需执行查询:

// 调试模式 - 返回 SqlTemplate
[SqlTemplate("SELECT * FROM users WHERE age >= @minAge")]
SqlTemplate GetAdultUsersSql(int minAge);

// 执行模式 - 返回数据
[SqlTemplate("SELECT * FROM users WHERE age >= @minAge")]
Task<List<User>> GetAdultUsersAsync(int minAge);

// 使用
var template = repo.GetAdultUsersSql(18);
Console.WriteLine(template.Sql);        // SELECT * FROM users WHERE age >= @minAge
Console.WriteLine(template.Parameters["@minAge"]);  // 18
Console.WriteLine(template.Execute().Render());     // SELECT * FROM users WHERE age >= 18

7. ADO.NET 集成

SqlTemplate 现在提供高性能 ADO.NET 扩展方法,让你可以直接执行 SQL 模板:

// 获取 SqlTemplate
var template = repo.GetUserByIdSql(123);

// 直接执行 - ExecuteScalar
int count = await template.ExecuteScalarAsync<int>(connection);
string? name = await template.ExecuteScalarAsync<string>(connection);

// ExecuteNonQuery
int rowsAffected = await template.ExecuteNonQueryAsync(connection);

// ExecuteReader
using var reader = await template.ExecuteReaderAsync(connection);
while (await reader.ReadAsync())
{
    // 处理数据...
}

// CreateCommand - 完全控制
using var cmd = template.CreateCommand(connection);
cmd.CommandTimeout = 30;
using var reader = await cmd.ExecuteReaderAsync();

// 参数覆盖 - 重用模板
var overrides = new Dictionary<string, object?> { ["@id"] = 456 };
var result = await template.ExecuteScalarAsync<string>(connection, parameterOverrides: overrides);

// 事务支持
using var transaction = connection.BeginTransaction();
await template.ExecuteNonQueryAsync(connection, transaction);
transaction.Commit();

性能特点:

  • ValueTask<T> - 零分配异步操作
  • 🔒 线程安全 - 不可变设计,无状态扩展
  • 🗑️ 低 GC 压力 - 最小内存分配
  • 🐛 调试友好 - 清晰的错误消息

性能对比 (基于 BenchmarkDotNet 真实测试数据): | 操作 | 手动 ADO.NET | SqlTemplate | 开销 | 内存分配 | |------|-------------|-------------|------|---------| | CreateCommand | 354.1 ns | 348.4 ns | -1.6% (更快!) | 392 B vs 424 B | | CreateCommand + Override | 354.1 ns | 398.4 ns | +12.5% | 392 B vs 664 B | | ExecuteScalar<int> | 49.8 μs | 51.3 μs | +3.0% | 944 B vs 1000 B | | ExecuteScalar<int> + Override | 49.8 μs | 49.6 μs | -0.4% (更快!) | 944 B vs 1240 B | | ExecuteScalar<string> | 4.32 μs | 4.76 μs | +10.2% | 952 B vs 984 B |

关键发现:

  • CreateCommand 性能相当,某些情况下甚至更快
  • 数据库操作开销极小(< 3-10%)
  • 参数覆盖功能增加约 12-31% 内存开销(字典查找成本)
  • 整体性能接近原生 ADO.NET

详细文档: SqlTemplate ADO.NET Integration


🗄️ 支持的数据库

数据库 状态 测试覆盖 特性支持
SQLite ✅ 生产就绪 100% 完整
PostgreSQL ✅ 生产就绪 100% 完整
MySQL ✅ 生产就绪 100% 完整
SQL Server ✅ 生产就绪 100% 完整
Oracle 🚧 实验性 80% 基础
DB2 🚧 实验性 60% 基础

📚 文档

快速入门

核心文档

高级特性

示例


🧪 测试覆盖率

Sqlx 拥有生产级别的测试覆盖率

  • 总测试数: 3,738 个测试
  • 核心库覆盖率: 88.6%
  • 测试通过率: 100%
  • 16 个类达到 100% 覆盖率

详细报告: FINAL_COVERAGE_REPORT.md


🚀 生产就绪

Sqlx 已经在多个生产环境中使用:

  • 高性能: 接近 ADO.NET 的性能
  • 低内存: 比 Dapper 节省 48-50% 内存
  • 类型安全: 编译时验证,零运行时错误
  • AOT 支持: 完全支持 Native AOT
  • 测试完善: 3,738 个测试,88.6% 覆盖率
  • 多数据库: 支持 4 种主流数据库

🤝 贡献

欢迎贡献!请查看 贡献指南


📄 许可证

MIT License


<div align="center">

Sqlx - 让数据访问回归简单,让性能接近极致! 🚀

Made with ❤️ by the Sqlx Team

GitHub · NuGet · 文档

</div>

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.6.8 95 2/7/2026
0.6.7 78 2/5/2026
0.6.6 79 2/3/2026
0.6.5 95 1/23/2026
0.6.4 87 1/22/2026
0.6.3 86 1/22/2026
0.6.2 99 1/16/2026
0.6.1 84 1/15/2026
0.6.0 83 1/15/2026
0.5.0 107 1/11/2026
0.4.0 213 10/27/2025
0.3.0 284 10/2/2025
0.2.0 227 9/21/2025
0.1.4-dev 210 8/31/2025
0.1.3-dev 118 8/23/2025
0.1.2-dev 177 8/20/2025
0.1.1-dev 149 8/17/2025
0.1.0-dev 164 7/27/2025

v0.4.0 - Major Update
     ✅ 100% Test Coverage: 963/963 tests passing
     🔗 JOIN Queries: INNER JOIN, LEFT JOIN, multi-table joins
     🎯 Advanced SQL: GROUP BY/HAVING, IN/LIKE/BETWEEN, CASE WHEN, DISTINCT
     💼 Transaction Support: Simple Repository.Transaction property API
     ⚡ Performance: 1.08-1.27x vs Dapper, better memory (-8% to -50%)
     🛡️ Robust: Large result sets, NULL handling, Unicode, connection reuse
     📚 Full documentation and migration guide available