Win10手记-为应用集成SQLite(二)
接上篇内容,这里给大家分享我的辅助访问类,采用了异步方法,封装了常用的访问操作,一些操作还是纯CLI的。
SQLiteDBManager
using System; using System.Collections.Generic; using System.Collections; using System.Threading.Tasks; using SQLite.Net; using SQLite.Net.Async; using Windows.Storage; using System.Diagnostics; using YunshouyiUWP.Model; namespace YunshouyiUWP.Data { public class SQLiteDBManager { private static SQLiteDBManager dbManager; /// <summary> /// construct function /// </summary> public SQLiteDBManager() { InitDBAsync(); } /// <summary> /// get current instance /// </summary> /// <returns></returns> public static SQLiteDBManager Instance() { if (dbManager == null) dbManager = new SQLiteDBManager(); return dbManager; } private static SQLiteAsyncConnection dbConnection; /// <summary> /// get current DBConnection /// </summary> /// <returns></returns> public async Task<SQLiteAsyncConnection> GetDbConnectionAsync() { if (dbConnection == null) { var path = await GetDBPathAsync(); dbConnection = new SQLiteAsyncConnection(() => new SQLiteConnectionWithLock(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), new SQLiteConnectionString(path, true))); } return dbConnection; } /// <summary> /// insert a item /// </summary> /// <param name="item">item</param> /// <returns></returns> public async Task<int> InsertAsync(object item) { try { var dbConnect = await GetDbConnectionAsync(); return await dbConnect.InsertOrReplaceAsync(item); } catch (Exception ex) { Debug.WriteLine(ex.Message); return -1; } } /// <summary> /// insert lots of items /// </summary> /// <param name="items">items</param> /// <returns></returns> public async Task<int> InsertAsync(IEnumerable items) { try { var dbConnect = await GetDbConnectionAsync(); return await dbConnect.InsertOrReplaceAllAsync(items); } catch (Exception ex) { Debug.WriteLine(ex.Message); return -1; } } /// <summary> /// find a item in database /// </summary> /// <typeparam name="T">type of item</typeparam> /// <param name="pk">item</param> /// <returns></returns> public async Task<T> FindAsync<T>(T pk) where T : class { try { var dbConnect = await GetDbConnectionAsync(); return await dbConnect.FindAsync<T>(pk); } catch (Exception ex) { Debug.WriteLine(ex.Message); return null; } } /// <summary> /// find a collection of items /// </summary> /// <typeparam name="T">type of item</typeparam> /// <param name="sql">sql command</param> /// <param name="parameters">sql command parameters</param> /// <returns></returns> public async Task<List<T>> FindAsync<T>(string sql, object[] parameters) where T : class { try { var dbConnect = await GetDbConnectionAsync(); return await dbConnect.QueryAsync<T>(sql, parameters); } catch (Exception ex) { Debug.WriteLine(ex.Message); return null; } } /// <summary> /// update item in table /// </summary> /// <typeparam name="T">type of item</typeparam> /// <param name="item">item</param> /// <returns></returns> public async Task<int> UpdateAsync<T>(T item) where T : class { try { var dbConnect = await GetDbConnectionAsync(); return await dbConnect.UpdateAsync(item); } catch (Exception ex) { Debug.WriteLine(ex.Message); return -1; } } /// <summary> /// update lots of items in table /// </summary> /// <typeparam name="T">type of item</typeparam> /// <param name="items">items</param> /// <returns></returns> public async Task<int> UpdateAsync<T>(IEnumerable items) where T : class { try { var dbConnect = await GetDbConnectionAsync(); return await dbConnect.UpdateAllAsync(items); } catch (Exception ex) { Debug.WriteLine(ex.Message); return -1; } } /// <summary> /// delete data from table /// </summary> /// <typeparam name="T">type of item</typeparam> /// <param name="item">item</param> /// <returns></returns> public async Task<int> DeleteAsync<T>(T item) where T : class { try { var dbConnect = await GetDbConnectionAsync(); return await dbConnect.DeleteAsync<T>(item); } catch (Exception ex) { Debug.WriteLine(ex.Message); return -1; } } /// <summary> /// delete all items in table /// </summary> /// <param name="t">type of item</param> /// <returns></returns> public async Task<int> DeleteAsync(Type t) { try { var dbConnect = await GetDbConnectionAsync(); return await dbConnect.DeleteAllAsync(t); } catch (Exception ex) { Debug.WriteLine(ex.Message); return -1; } } /// <summary> /// get local path in application local folder /// </summary> /// <returns></returns> private async Task<string> GetDBPathAsync() { var file = await ApplicationData.Current.LocalFolder.GetFileAsync("db.sqlite"); if (file == null) { var dbFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Data/db.sqlite")); file = await dbFile.CopyAsync(ApplicationData.Current.LocalFolder); } return file.Path; } /// <summary> /// init db /// </summary> private static async void InitDBAsync() { try { var file = await ApplicationData.Current.LocalFolder.TryGetItemAsync("db.sqlite"); if (file == null) { var dbFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Data/db.sqlite")); file = await dbFile.CopyAsync(ApplicationData.Current.LocalFolder); var dbConnect = new SQLiteAsyncConnection(() => new SQLiteConnectionWithLock(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), new SQLiteConnectionString(file.Path, true))); var result = await dbConnect.CreateTablesAsync(new Type[] { typeof(Fund), typeof(P2P) }); Debug.WriteLine(result); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } } }
使用方法
以查找数据为例,如下:
public async Task<List<Fund>> GetFundDataAsync() { var result = await SQLiteDBManager.Instance().FindAsync<Fund>("select * from Fund where Id=?", new string[] { Guid.NewGuid().ToString() }); if (result != null) return result; return null; }
初始化数据库时可以一次性创建需要的表,我创建的表如下:
注意事项
1.要为项目引入SQLite.Net.Async-PCL以及VC++ runtime类库,如下:
2.具体操作SQLite方法请查看SQLite.Net项目详细说明,地址如下:
https://github.com/oysteinkrog/SQLite.Net-PCL
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?