zoukankan      html  css  js  c++  java
  • 【Android】13.4 使用SQLite.NET.Async-PCL访问SQLite数据库

    分类:C#、Android、VS2015;

    创建日期:2016-02-27

    一、简介

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

    二、示例4运行截图

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

    image  image

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

    image  image

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

    三、主要设计步骤

    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}]
    ",
                    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} 条记录。
    ";
                        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} 条记录。
    ";
                        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}
    ";
                var data = await conn.Table<Student>().ToListAsync();
                foreach (var v in data)
                {
                    s += v.ToString();
                }
                return s;
            }
        }
    }
  • 相关阅读:
    urllib使用四--urlencode,urlparse,
    urllib使用三--urlretrieve下载文件
    urllib使用二
    urllib使用一
    python使用网易邮箱发邮件
    python QQ邮件发送邮件
    可以字符串string转化成list,tuple,dict的eval()方法
    一行代码将两个列表拼接出第三个列表(两个可迭代对象相加产生第三个可迭代对象)--map()方法
    把列表中的元素拼接成字符串
    Runtime 类
  • 原文地址:https://www.cnblogs.com/rainmj/p/5222476.html
Copyright © 2011-2022 走看看