DI魅力渐显_依赖注入\Program.cs
| services.AddScoped<IDbConnection>(sp => { |
| string connStr = "Data Source=test.db"; |
| var conn = new SqliteConnection(connStr); |
| conn.Open(); |
| return conn; |
| }); |
DI魅力渐显_依赖注入\UserDAO.cs
| private readonly IDbConnection conn; |
| using var dt = SqlHelper.ExecuteQuery(conn,$"select * from T_Users where UserName={userName}"); |
DI魅力渐显_依赖注入\SqlHelper.cs
| using System.Data; |
| namespace DI魅力渐显_依赖注入 |
| { |
| static class SqlHelper |
| { |
| |
| public static DataTable ExecuteQuery(this IDbConnection conn, FormattableString formattable) |
| { |
| using IDbCommand cmd = CreateCommand(conn, formattable); |
| DataTable dt = new DataTable(); |
| using var reader = cmd.ExecuteReader(); |
| dt.Load(reader); |
| return dt; |
| } |
| |
| public static object? ExecuteScalar(this IDbConnection conn, FormattableString formattable) |
| { |
| using IDbCommand cmd = CreateCommand(conn, formattable); |
| return cmd.ExecuteScalar(); |
| } |
| |
| public static int ExecuteNonQuery(this IDbConnection conn, FormattableString formattable) |
| { |
| using IDbCommand cmd = CreateCommand(conn, formattable); |
| int result = cmd.ExecuteNonQuery(); |
| return result; |
| } |
| |
| private static IDbCommand CreateCommand(IDbConnection conn, FormattableString formattable) |
| { |
| var cmd = conn.CreateCommand(); |
| string sql = formattable.Format; |
| for (int i = 0; i < formattable.ArgumentCount; i++) |
| { |
| sql = sql.Replace("{" + i + "}", "@p" + i); |
| var parameter = cmd.CreateParameter(); |
| parameter.ParameterName = "@p" + i; |
| parameter.Value = formattable.GetArgument(i); |
| cmd.Parameters.Add(parameter); |
| } |
| cmd.CommandText = sql; |
| return cmd; |
| } |
| } |
| } |
| |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
2023-02-10 sqlalchemy_fastapi_demo
2023-02-10 sqlalchemy_sqlite_shellhistory
2022-02-10 for循环中使用异步请求的注意
2022-02-10 promise 成功回调 失败回调
2022-02-10 reduce中使用request请求
2022-02-10 常见的数据操作 封装成一个对象处理
2022-02-10 nodejs中的request请求 promise封装