13.4 使用SQLite.NET.Async-PCL访问SQLite数据库

分类:C#、Android、VS2015;

创建日期:2016-02-27

一、简介

这一节演示如何利用以异步方式(async、await)访问SQLite数据库。

二、示例4运行截图

下面左图为初始页面,右图为单击【创建数据库】按钮后的结果。

 

下面左图为单击【添加单行】按钮的结果,右图为单击【添加多行】按钮的结果。

 

注意:不想再像上一节的例子那样逐个添加页面了,毕竟例子的目的仅仅是为了演示最基本的异步操作用法,代码太多容易冲淡要关注的内容,所以该例子并没有去解决重复添加相同学号的记录引起的冲突问题,只是简单地把捕获的异常直接显示出来了。但是,在实际项目中,你如果也像这个例子这样去简单处理,那你肯定会挨训,呵呵。

三、主要设计步骤

1、添加对SQLite.NET.Async-PCL程序包的引用

鼠标右击项目中的【引用】à【管理NuGet程序包】,数据源选择【NuGet official package source】,在搜索框中输入【sqlite】,找到【SQLite.NET.Async-PCL】,选择最新的版本(本示例使用的是3.1.1版),然后单击【安装】。

安装程序包以后,在【解决方案资源管理器】中,就可以看出它已经替你自动添加了对SQLite.Net.Async的引用。安装的程序包及其依赖项的名称和版本见本章开头(13.0节)列出的packages.config文件。

2、创建数据库和表

在SrcDemos文件夹下添加一个MyDb4Model文件夹,该文件夹用于保存与“MyDb4.db”数据库相关的.cs文件。

(1)添加Student.cs文件

using System;
using SQLite.Net.Attributes;

namespace MyDemos.SrcDemos.MyDb4Model
{
    [Table("Student")]
    public class Student
    {
        //主键,自动增量
        [PrimaryKey,AutoIncrement]
        public int id { get; set; }

        //学号
        [Unique, NotNull]
        public string XueHao { get; set; }

        //姓名
        [MaxLength(30), NotNull]
        public string Name { get; set; }

        //出生日期
        public DateTime BirthDate { get; set; }

        public override string ToString()
        {
            return string.Format(
                "[学号={0}, 姓名={1}, 出生日期={2:yyyy-MM-dd}]\n",
                XueHao, Name, BirthDate);
        }
    }
}

(2)添加MyDb4.cs文件

using System;
using System.IO;
using SQLite.Net;
using SQLite.Net.Async;
using SQLite.Net.Platform.XamarinAndroid;

namespace MyDemos.SrcDemos.MyDb4Model
{
    public static class MyDb4
    {
        private static readonly string dbPath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.Personal),
            "MyDb4.db");

        public static SQLiteAsyncConnection GetAsyncConnection()
        {
            SQLitePlatformAndroid platform = new SQLitePlatformAndroid();
            SQLiteConnectionString connStr = new SQLiteConnectionString(dbPath, false);
            return new SQLiteAsyncConnection(()=> new SQLiteConnectionWithLock(platform, connStr));
        }
    }
}

3、添加ch1304_Main.axml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1">
    <LinearLayout
        android:orientation="horizontal"
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout1"
        android:layout_weight=".2"
        android:gravity="center">
        <Button
            android:text="创建数据库"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnCreateDB" />
        <Button
            android:text="添加单行"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnCreateSingle" />
        <Button
            android:text="添加多行"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnCreateList" />
    </LinearLayout>
    <LinearLayout
        android:orientation="vertical"
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout2"
        android:layout_weight="0.6"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp">
        <TextView
            android:text="结果"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView1"
            android:textColor="#fff" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/txtResults"
            android:layout_marginTop="5dp" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout3"
        android:layout_weight="0.2" />
</LinearLayout>

4、添加ch1304MainActivity.cs文件

using System;
using System.Collections.Generic;
using Android.App;
using Android.OS;
using Android.Widget;
using MyDemos.SrcDemos.MyDb4Model;
using SQLite.Net;
using System.Threading.Tasks;

namespace MyDemos.SrcDemos
{
    [Activity(Label = "【例13-4】SQLite基本用法4")]
    public class ch1304MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.ch1304_Main);

            var btnCreate = FindViewById<Button>(Resource.Id.btnCreateDB);
            var btnSingle = FindViewById<Button>(Resource.Id.btnCreateSingle);
            var btnList = FindViewById<Button>(Resource.Id.btnCreateList);
            var txtResult = FindViewById<TextView>(Resource.Id.txtResults);

            // 数据库创建之前禁用相关按钮
            btnSingle.Enabled = btnList.Enabled = false;

            btnCreate.Click += async delegate
            {
                try
                {
                    var conn = MyDb4.GetAsyncConnection();
                    await conn.CreateTableAsync<Student>();
                    await conn.DeleteAllAsync<Student>();
                    txtResult.Text = "创建成功。";
                    btnList.Enabled = btnSingle.Enabled = true;
                }
                catch (SQLiteException ex)
                {
                    txtResult.Text = "创建失败:" + ex.Message;
                }
            };

            btnSingle.Click += async delegate
            {
                var student = new Student { XueHao = "01001", Name = "张三", BirthDate = new DateTime(1995, 4, 7) };
                try
                {
                    var conn = MyDb4.GetAsyncConnection();
                    int x = await conn.InsertAsync(student);
                    await conn.UpdateAsync(student);
                    txtResult.Text = $"添加了 {x} 条记录。\n";
                    txtResult.Text += await GetStudents();
                }
                catch (SQLiteException ex)
                {
                    txtResult.Text = "Error:" + ex.Message;
                }
            };

            btnList.Click += async delegate
            {
                var list = new List<Student>{
                    new Student { XueHao="01002", Name = "李四", BirthDate = new DateTime(1995,4,8) },
                    new Student { XueHao="01003", Name = "王五", BirthDate = new DateTime(1995,4,9) },
                    new Student { XueHao="01004", Name = "赵六", BirthDate = new DateTime(1995,4,10) }
                };
                try
                {
                    var conn = MyDb4.GetAsyncConnection();
                    int x = await conn.InsertAllAsync(list);
                    await conn.UpdateAllAsync(list);
                    txtResult.Text = $"添加了 {x} 条记录。\n";
                    txtResult.Text += await GetStudents();
                }
                catch (SQLiteException ex)
                {
                    txtResult.Text = "Error:" + ex.Message;
                }
            };
        }

        private static async Task<string> GetStudents()
        {
            var conn = MyDb4.GetAsyncConnection();
            int count = await conn.Table<Student>().CountAsync();
            string s = $"当前记录数:{count}\n";
            var data = await conn.Table<Student>().ToListAsync();
            foreach (var v in data)
            {
                s += v.ToString();
            }
            return s;
        }
    }
}
时间: 2024-08-05 14:55:58

13.4 使用SQLite.NET.Async-PCL访问SQLite数据库的相关文章

【Android】13.0 第13章 创建和访问SQLite数据库&mdash;本章示例主界面

分类:C#.Android.VS2015: 创建日期:2016-02-26 一.简介 Android 内置了三种数据存取方式:SQLite数据库.文件.SharedPreferences. 这一章我们主要学习如何使用SQLite数据库存取数据. 1.SQLite是个什么档次的数据库 SQLite是一种免费的.开源的数据库,由于它独特的设计(把各种数据类型都转换为它自己内部处理的5种类型)导致其占用内存极少,因此很多项目都喜欢使用它. Android集成了SQLite并内置了专门对SQLite操作

13 使类和成员的可访问性最小化

要区别设计良好的模块与设计不好的模块,最重要的因素在于,这个模块对于外部的其他模块而言,是否隐藏其内部数据和其他实现细节.设计良好的模块会隐藏所有的实现细节,把它的API与它的实现清晰地隔离开来. 信息隐藏之所以非常重要有许多原因,其中大多数理由都源于这样一个事实:它可以有效的解除组成系统的各个模块之间的耦合关系,使得这些模块可以独立地开发.测试.优化.使用.理解和修改. 第一个规则很简单:尽可能地使每个类或者成员不被外界访问. 对于顶层的(非嵌套)的类和接口,只有两种可能的访问级别:包级私有的

SQLitedatabase实现访问sqlite

通过SQLiteDatabase 来访问sqlite数据库 ----Main.java public class Main extends Activity { SQLiteDatabase db; ListView listView; EditText editText1, editText2;  //要添加的标题和context Button button; @Override protected void onCreate(Bundle savedInstanceState) { supe

Objective-C访问SQLite

数据库的相关知识我就不去说明了,毕竟只要会sql语言的人就大家都一样. 本案例是在Xcode7.2环境下创建的single view application进行演示操作. 首先第一点,为什么要使用sqlite3? 在iOS的编程中,毫无疑问接触最多的就是界面的代码编排和设计,数据的解析与放置,算法的各种挠头问题... 在数据的解析与放置这一块,就会涉及到数据库缓存的操作,我们都知道,iOS手机编程是在手机端运行的,你不能老是去服务器端读取数据啊,好,就算你不烦,手机也跑的起来,流量不要过啊,对于

应用EF访问SQLite数据

1.创建项目 项目结构初始结构如下图所示,Netage.Data.SQLite 类库项目用于定义访问数据的接口和方法,Netage.SQLiteTest.UI 控制台项目引用 Netage.Data.SQLite 类库,调用其相应的方法来访问数据. 2.在项目中加入SQLite类库 右键 Netage.Data.SQLite 项目,选择"Manage Nuget Packages"菜单,在输入框中输入"System.Data.SQLite",查询到"Sys

java文件来演示如何访问MySQL数据库

java文件来演示如何访问MySQL数据库. 注:在命令行或用一个SQL的前端软件创建Database. 先创建数据库: CREATE DATABASE SCUTCS; 接着,创建表: CREATE TABLE STUDENT ( SNO CHAR(7) NOT NULL, SNAME VARCHAR(8) NOT NULL, SEX CHAR(2) NOT NULL, BDATE DATE NOT NULL, HEIGHT DEC(5,2) DEFAULT 000.00, PRIMARY KE

【玩转SQLite系列】(一)初识SQLite,重拾sql语句

转载请注明出处:http://blog.csdn.net/linglongxin24/article/details/53230842 本文出自[DylanAndroid的博客] [玩转SQLite系列](一)初识SQLite,重拾sql语句 SQLite由于是一个轻型的嵌入式的数据库,被应用于Android系统当中.在Android开发中 我们难免会用到SQLite数据库.接下来用一系列的文章来数据一下SQLite数据库. 一.认识SQLite 1.什么是SQLite SQLite,是一款轻型

C#访问MySQL数据库(winform+EF)

原文:C#访问MySQL数据库(winform+EF) 以前都是C#连接SQLServer,现在MySQL也比较火了,而且是开源跨平台的,这里连接使用一下,主要是体会一下整个流程,这里使用的是winform 访问MYSQL,当然使用winfrom,还是wfp,以及其他的技术这里不讨论,个人觉得这个比较上手快. http://jingyan.baidu.com/article/642c9d34aa809a644a46f717.html 1.安装MYSQl数据库,这里略过,可以参考此文档进行安装.

js中访问SqlServer数据库

1 <script language="JavaScript"> 2 // 创建数据库对象 3 var objdbConn = new ActiveXObject("ADODB.Connection"); 4 // DSN字符串 5 var strdsn = "Driver={SQL Server};SERVER=127.0.0.1;UID=sa;PWD=sa;DATABASE=coa"; 6 // 打开数据源 7 objdbConn