目的:使用 SQLiteDatabase 创建本地数据库、表,并对数据进行增删改查操作。

引用命名空间:

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Database.Sqlite;
using Android.Content;
using System.IO;
using System.Data;
using Mono.Data.Sqlite;
using System;
using Android.Database;
using System.Collections.Generic;

Person类

public class Person
{
public string Id { get; set; }
public string Name { get; set; }
public string IdCard { get; set; }
public string Sex { get; set; }
public string Age { get; set; }
}

创建局部变量Localhost_DataBase,以及控件,model类

SQLiteDatabase Localhost_DataBase = null;

Person person;
List<Person> list = new List<Person>();
ListView lv_Person;

创建数据库

/// <summary>
/// 创建数据库
/// </summary>
void CreateDataBase()
{
try
{
//打开或创建数据库 名称为:AssetsManage.db
Localhost_DataBase = OpenOrCreateDatabase("AssetsManage.db", FileCreationMode.Private, null); //判断是否存在数据库
if (string.IsNullOrEmpty(GetSharedPreferences("AssetsManage", ).GetString("AssetsManage", "")))//未创建数据库
{
File.Create(Localhost_DataBase.Path);
//继续创建数据表
CreateTable();
//存取已创建数据库信息
GetSharedPreferences("AssetsManage", ).Edit().PutString("AssetsManage", "OK").Commit();
}
}
catch
{
//存取创建数据库时的异常
GetSharedPreferences("Exception", ).Edit().PutString("DataBaseException", "异常").Commit();
}
}

创建表

/// <summary>
/// 创建表
/// </summary>
void CreateTable()
{
string db = Localhost_DataBase.Path;
var conn = new SqliteConnection("Data Source=" + db);
//这里可以创建多张表
var commands = new[] {
"CREATE TABLE tb_person (Id int,name varchar(20),sex varchar(80),age varchar(20),idcard varchar(18))", "CREATE TABLE tb_grade (uId int,mathgrade varchar(5),Chinese varchar(5),English varchar(5))"
};
try
{
foreach (var cmd in commands)
{
using (var sqlitecmd = conn.CreateCommand())
{
sqlitecmd.CommandText = cmd;
sqlitecmd.CommandType = CommandType.Text;
conn.Open();
sqlitecmd.ExecuteNonQuery();
conn.Close();
}
} InsertData();
}
catch (System.Exception e)
{
//存取创建数据表时的异常
GetSharedPreferences("Exception", ).Edit().PutString("DataTableException", "异常").Commit();
}
}

向表中插入模拟数据

/// <summary>
/// 插入数据
/// </summary>
void InsertData()
{
for(int i=;i<=;i++)
{
ContentValues cv = new ContentValues();
cv.Put("Id", i.ToString());
cv.Put("name", "张三" + i.ToString());
cv.Put("sex", new Random().Next(, ) == ? "男" : "女");
cv.Put("age", ( + i).ToString());
cv.Put("idcard", "" + (i - ).ToString());
Localhost_DataBase.Insert("tb_person", null, cv); ContentValues cv1 = new ContentValues();
cv1.Put("uId", i);
cv1.Put("mathgrade", new Random().Next(, ));
cv1.Put("Chinese", new Random().Next(, ));
cv1.Put("English", new Random().Next(, ));
Localhost_DataBase.Insert("tb_grade", null, cv1);
}
}

查询表中数据

/// <summary>
/// 查询数据
/// </summary>
void QueryData()
{
ICursor ic = Localhost_DataBase.Query("tb_person", null, null, null, null, null, null); //全部查询
//ICursor ic = Localhost_DataBase.Query("tb_person", null, " id =? and name =?", new string[] { "1","张三1" }, null, null, null); //条件查询
for (int i = ; i < ic.Count; i++)
{
if (i == ) //确定游标位置
{
ic.MoveToFirst();
}
else
{
ic.MoveToNext();
} person = new Person();
person.Id = ic.GetString(ic.GetColumnIndex("Id"));
person.Name = ic.GetString(ic.GetColumnIndex("name"));
person.Age = ic.GetString(ic.GetColumnIndex("age"));
person.Sex= ic.GetString(ic.GetColumnIndex("sex"));
person.IdCard = ic.GetString(ic.GetColumnIndex("idcard"));
list.Add(person);
}
lv_Person.Adapter = new ListViewAdapter(this, list);
}

根据条件删除表中数据

/// <summary>
/// 删除数据
/// </summary>
/// <param name="id"></param>
void DeleteData(string id)
{
Localhost_DataBase.Delete("tb_person", " Id=?", new string[] { id });
//Localhost_DataBase.Delete("tb_person", null, null); //删除表中所有数据
}

根据条件修改表中数据

/// <summary>
/// 修改数据
/// </summary>
/// <param name="name"></param>
void UpdateData(string id)
{
ContentValues cv = new ContentValues();
cv.Put("name", "张三1000");
Localhost_DataBase.Update("tb_person", cv, " Id=? ", new string[] { id });
}

ListViewAdapter 类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget; namespace LocalhostDataBaseTest
{
public class ListViewAdapter:BaseAdapter<Person>
{
Activity context;
public List<Person> mings; public ListViewAdapter(Activity context, List<Person> mings)
{
this.context = context;
this.mings = mings;
} public override int Count
{
get
{
return this.mings.Count;
}
} public override long GetItemId(int position)
{
return position;
} public override Person this[int position]
{
get
{
return this.mings[position];
}
} public override View GetView(int position, View convertView, ViewGroup parent)
{
var itme = this.mings[position]; convertView = LayoutInflater.From(context).Inflate(Resource.Layout.Person_Items, parent, false); TextView item_id = convertView.FindViewById<TextView>(Resource.Id.item_id);
TextView item_name = convertView.FindViewById<TextView>(Resource.Id.item_name);
TextView item_idcard = convertView.FindViewById<TextView>(Resource.Id.item_idcard);
TextView item_sex = convertView.FindViewById<TextView>(Resource.Id.item_sex);
TextView item_age = convertView.FindViewById<TextView>(Resource.Id.item_age); item_id.Text = (position + ).ToString();
item_name.SetText(itme.Name, TextView.BufferType.Normal);
item_idcard.SetText(itme.IdCard, TextView.BufferType.Normal);
item_sex.SetText(itme.Sex, TextView.BufferType.Normal);
item_age.SetText(itme.Age, TextView.BufferType.Normal); return convertView;
}
}
}

OnCreate调用

protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main); lv_Person = FindViewById<ListView>(Resource.Id.listViewPerson);
CreateDataBase();
DeleteData("");
UpdateData("");
QueryData();
}

到这里就结束了,那里写的不足希望大家补充~

链接: https://pan.baidu.com/s/1QhDkfSXyVlmWEnIU6VGy-g

密码: isa8

Xamarin.Android 本地数据库 SQLiteDatabase 操作的更多相关文章

  1. android本地数据库,微信数据库WCDB for Android 使用实例

    android本地数据库,微信数据库WCDB for Android 使用实例 Home · Tencent/wcdb Wikihttps://github.com/Tencent/wcdb/wiki ...

  2. android 本地数据库sqlite的封装

    单机android   sqlite数据库的实现,这个数据库可与程序一起生成在安装包中 一.下载sqlite3.exe文件 二.运行 cmd 转到sqlite3.exe 所在目录  运行 sqlite ...

  3. Windows Phone开发(48):不可或缺的本地数据库

    原文:Windows Phone开发(48):不可或缺的本地数据库 也许WP7的时候,是想着让云服务露两手,故似乎并不支持本地数据库,所有数据都上传上"云"数据库中.不过呢,在SD ...

  4. SQLCE本地数据库

    SQLCE是一个标准得关系数据库,可以使用 LINQ 和DateContext来处理本地数据库数据库. 使用SQLCE 要在代码中使用本地数据库功能,需要添加以下命名空间 : using System ...

  5. Xamarin.Android 使用 SQLiteOpenHelper 进行数据库操作

    一.前言 在手机中进行网络连接不仅是耗时也是耗电的,而耗电却是致命的.所以我们就需要数据库帮助我们存储离线数据,以便在用户未使用网络的情况下也可以能够使用应用的部分功能,而在需要网络连接的功能上采用提 ...

  6. Android本地数据存储之SQLite关系型数据库 ——SQLiteDatabase

    数据库的创建,获取,执行sql语句: 框架搭建:dao 思考: 1.数据库保存在哪里? 2.如何创建数据库?如何创建表? 3.如何更新数据库?如何更改表的列数据? 4.如何获取数据库? 5.如何修改数 ...

  7. Xamarin android 的WebClient Json下载并存储本地及sqlite数据库

    这一点雕虫小技可能对熟悉的人来说已经不值一提.但是我想,既然这些都是常用的功能,集成在一起做个笔记也有点意义吧. 首先,json 是传递数据的事实标准了.所以先说一下将它从服务器端下载下来..net ...

  8. Xamarin android使用Sqlite做本地存储数据库

    android使用Sqlite做本地存储非常常见(打个比方就像是浏览器要做本地存储使用LocalStorage,貌似不是很恰当,大概就是这个意思). SQLite 是一个软件库,实现了自给自足的.无服 ...

  9. 【转】Android动态破解微信本地数据库(EnMicroMsg.db)

    最近在公司接了一个任务,需要在几百台手机上安装一个app,目的是获取微信里面的通讯录,并且定时的把他发送到我们的服务器上.当时依次尝试的如下几个方案: 1.通过群控,将好友截图发送到服务端(pytho ...

随机推荐

  1. php json 写入 mysql 的例子

    $a['aaa']='aaaa'; $a['bbb']='bbb'; $a['ccc']='ccc'; $arr['step_name']='kfkf'; $arr['process_name']=' ...

  2. 9. Palindrome Number (JAVA)

    Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same back ...

  3. [leetcode]87. Scramble String字符串树形颠倒匹配

    Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrin ...

  4. Spring Kafka中关于Kafka的配置参数

    #################consumer的配置参数(开始)################# #如果'enable.auto.commit'为true,则消费者偏移自动提交给Kafka的频率 ...

  5. Git-git push -u为何第二次不用指定-u?

    1,如果当前分支只有一个追踪分支,那么主机名都可以省略,如:git push origin 将当前分支推送到origin主机的对应分支 2,$ git push 如果当前分支与多个主机存在追踪关系,那 ...

  6. sublime text3 使用问题积累

    1.安装完后,注册码:注意!要把下列内容完全拷贝过去,包含"-------BEGIN LICENSE------和------END LICENSE--------" ----- ...

  7. ES6自我总结笔记(阮一峰ES6入门)

    [let和const命令] 1.var的作用域是函数体内,不是块级作用域 2.let是更完美的var,let的变量的作用是块级作用域 3.let声明的全局变量不是全局对象属性,不可以通过window. ...

  8. JS的事件流的概念(重点)

      09-JS的事件流的概念(重点)   在学习jQuery的事件之前,大家必须要对JS的事件有所了解.看下文 事件的概念 HTML中与javascript交互是通过事件驱动来实现的,例如鼠标点击事件 ...

  9. SpringMVC Http请求工具代码类

    在SpringMVC的源代码中也提供了一个封装过的ThreadLocal,其中保存了每次请求的HttpServletRequest对象,(详细请看org.springframework.web.con ...

  10. Hadoop学习之路(二十三)MapReduce中的shuffle详解

    概述 1.MapReduce 中,mapper 阶段处理的数据如何传递给 reducer 阶段,是 MapReduce 框架中 最关键的一个流程,这个流程就叫 Shuffle 2.Shuffle: 数 ...