Using SQLite database in your Windows 10 apps

MVP可以在channel 9上传视频了,所以准备做个英文视频传上去分享给大家,本文做稿子。

Hello everyone,

As we all know, SQLite is a great and popular local database running one mobile devices. Consider of its powerful and useful features, lots of apps use SQLite database as the main way of application data storage, including Android and iOS apps. What‘s more, SQLite is cross-platform database and also have windows version so that windows apps are easy to integrate with it. Today I will give a lesson about using SQLite in UWP project.

Install

Firstly, it‘s necessary for us to install SQLite for windows. you can download the binary install file here. Actually, you can alse download the source and build it for youself, if you like source more. After you finnished installation, you can find the sqlite extension in the refrence window. It will look like this:

And we need to add the VC++ 2015 Runtime refrence too.

 Project Configuration

Secondly, we need to add a framework named SQLite.Net for using SQLite effectively. In other words, SQLite.Net libary will help us access sqlite database more esaily. It have some relese versions which you can find in NuGet, and two of them are most useful, including SQLite.Net-PCL and SQLite.Net.Async-PCL.

What‘s the defference between SQLite.Net-PCL and SQLite.Net.Async-PCL framework is that SQLite.Net.Async-PCL support asynchronous operations. Actually I like async-await more, so I will install SQLite.Net.Async-PCL framework. Once we finish configurations, we can write some code to use SQLite now.

SQLiteDBManager

Let‘s we have some interesting codes to begin using this amazing tool now. What‘s more, I will provide some example codes written by myself for you. The mainly code is used to manager local SQLite database file and access it more easily, so I named it SQLiteDBMnager.

Before we access the data of database, we need import and manage the database file. In windows runtime framework we need to move or create database file in ApplicationData folder. And you can create a database file using SQLite Expert which is famous manage tool for SQLite database.

/// <summary>
        /// init db
        /// </summary>
        private static async void InitDBAsync()
        {
            try
            {
                var file = await ApplicationData.Current.LocalFolder.TryGetItemAsync("ysy.sqlite");
                if (file == null)
                {
                    var dbFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Data/ysy.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)));
                    //create db tables
                    var result = await dbConnect.CreateTablesAsync(new Type[] { typeof(Product), typeof(P2PData), typeof(ProductDetail), typeof(P2PDataDetail), typeof(ProductExtend), typeof(P2PDataExtend) });
                    Debug.WriteLine(result);
                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);

            }
        }

After we initialize database, we need to access the data of database. Fortunately, SQLite.NET provides some method for us, but we still do some works to simplify codes.

/// <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;
        }

Add/Delete/Modify/Find

/// <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;
            }
        }

Last but not least, we can access the database easily. For example,

 /// <summary>
        /// get product tabele data
        /// </summary>
        /// <returns></returns>
        private async Task<List<Fund>> GetFundDataFromDataBaseAsync()
        {
            var manager = SQLiteDBManager.Instance();
            var funds =new List<Fund>();
            var products = await manager.FindAsync<Product>("select * from Product", null);
            products.ForEach(p => {
                funds.Add(new Fund { Id=p.ProductId.ToString(), Host=p.Company, Image=p.Icon, Name=p.Name, Platform=p.FoundationName, QRNH=p.QRNH, WFSY=p.WFSY });
            });
            if (funds != null && funds.Count > 0)
            {
                return funds;
            }
            return null;
        }

You can get entire file here.

Conclusion

SQLite database is a good choice as application data storage container, and more excellent that ApplicationSettings and Xml/Json data files in many ways, I think.

时间: 2025-01-13 02:15:04

Using SQLite database in your Windows 10 apps的相关文章

微软官方WINDOWS 10部署资料链接地址:Deploy Windows 10 with the Microsoft Deployment Toolkit

微软官方WINDOWS 10部署资料,写的非常详细,包括部署平台建立.镜像导入.样本机制作.应用程序安装.硬件驱动识别.WIN7升级等,是一个非常好的利用MDT 2013 UPDATE 1部署WINDOWS 10的资料,推荐阅读,难度中等. 链接地址:https://technet.microsoft.com/en-us/library/mt297535(v=vs.85).aspx Deploy Windows 10 with the Microsoft Deployment Toolkit 1

设置UWP程序自启动(Automate launching Windows 10 UWP apps)

原文:设置UWP程序自启动(Automate launching Windows 10 UWP apps) 在开发UWP程序的过程中,有时候需要设置程序的自启.本人实现的步骤如下: 1.在VS中激活Protocol (Package.appxmanifest --> Declarations --> Add Protocol),图示如下: 2.编译并发布项目(Build and Deploy) 发布之后Protocol被激活,在(控制面板 --> 程序 --> 默认程序 -->

Build better apps: Windows 10 by 10 development series

http://blogs.windows.com/buildingapps/2015/08/05/build-better-apps-windows-10-by-10-development-series/ We’ve been talking about the new capabilities that come with Windows 10 for some time, but an area that we haven’t really dug into yet is how they

UWP深入学习五:Build better apps: Windows 10 by 10 development series

Promotion in the Windows Store  In this article, I walk through how to Give your Store listing a makeover, Start measuring your success(using the Visual Studio Application Insights SDK in your app), and Start promoting your APP. Live Tiles and Notifi

DB 查询分析器 6.04 在 Windows 10 上的安装与运行展示

DB查询分析器 6.04 在 Windows 10 上的安装与运行展示 中国本土程序员马根峰(CSDN专访马根峰:海量数据处理与分析大师的中国本土程序员 http://www.csdn.net/article/2014-08-09/2821124)推出的个人作品----万能数据库查询分析器,中文版本<DB 查询分析器>.英文版本<DB QueryAnalyzer>.它具有强大的功能.友好的操作界面.良好的操作性.跨越各种数据库平台乃至于EXCEL和文本文件. 你可以通过它 ① 查询

[转]Android Studio SQLite Database Example

本文转自:http://instinctcoder.com/android-studio-sqlite-database-example/ BY TAN WOON HOW · PUBLISHED APRIL 9, 2014 · UPDATED JUNE 23, 2016 SQLiteDatabase is a class that allowed us to perform Create, Retrieve , Update, and Delete data (CRUD) operation.

What is the purpose for IT Pro in Windows 10 Creators Update

Windows 10, version 1703-also known as the Windows 10 Creators Update-is designed for today's modern IT environment with new features to help IT pros more easily manage, and better protect, the devices and data in their organizations. It also provide

TroubleShoot: Enable Developer Mode in Windows 10 Insider Preview Build 10074

There is a known issue in Windows 10 Insider Preview build 10074 (see here). Developers cannot enable Developer Mode in the Settings app for installing and testing apps on this build. We’ll enable this in an upcoming build. In the meantime, you will

Windows 10 发布:微软的回归与前进

“我们希望,所有Windows 7用户都能有这样的感觉:昨天他们还开着第一代普锐斯,而今天Windows 10就将让他们觉得像是开上了特斯拉.” 今天凌晨,微软发布了新一代操作系统 Windows 10,有趣的是,上一版的名称是 Windows 8,也就是说,实际上微软是跳过了 Windows 9.虽然从系统命名来看,似乎这个新系统发布是一次大跃进,但是从界面来讲,却是一次回归.香格里拉娱乐城 值得注意的是,从4英寸屏幕的“迷你”手机到10英寸的普通平板以及14英寸的笔记本.再到80英寸的巨屏电