目的:使用 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. trap实现跳板机

    第一节 跳板机实现原理(图例) 第2节 涉及到的知识点 命令:trap 拓展知识:进程与信号 trap 语法,作用,使用 [jeson@mage-jump-01 ~/]$  trap -l  1) S ...

  2. 语义分割之Dual Attention Network for Scene Segmentation

    Dual Attention Network for Scene Segmentation 在本文中,我们通过 基于自我约束机制捕获丰富的上下文依赖关系来解决场景分割任务.       与之前通过多尺 ...

  3. Python的基本用法

    ---恢复内容开始--- 一.函数 1.1 默认参数 想要计算一个数x的n次方,可以定义如下的函数.但是有时候我们仅仅只需要计算x^2,所以只想使用一个参数即power(x),这时如果仍用如下代码会报 ...

  4. 加NONCLUSTERED INDEX索引,在ON了之后还要INCLUDE

    之前加了索引,但效果不大 SET STATISTICS TIME ON --执行时间 SET STATISTICS IO ON --IO读取 DBCC DROPCLEANBUFFERS --清除缓冲区 ...

  5. [leetcode]62. Unique Paths 不同路径

    A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The ...

  6. Ubuntu 18.04学习笔记

    命令行快捷键 https://blog.csdn.net/wanlhr/article/details/80926804 Ubuntu18.04使用vi命令修改文件并保存 vi /opt/teamvi ...

  7. 腾讯云主机的公网无法访问,putty和FileZilla连接不上

    1.解决方法一(之前百度都是这种安全组忘了添加) 2.解决方案二(ps:我是用centos的,然后不知道为什么访问不了,端口也是全部开的) service network restart 重置网络命令 ...

  8. 快速创建IIS站点并设置权限

     net user WebSiteUser WebSiteUserWebSiteUser /add /yWMIC Path Win32_UserAccount Where Name="Web ...

  9. ajax的另一种成功和失败回调函数

    第一种: function engline(){ var oldmsg = $('#lineso').val() if(oldmsg == null || oldmsg == '' || oldmsg ...

  10. 还原Azure DevOps Server (TFS)中误删除的生成流水线

    流水线历史记录 DevOps Server流水线的历史记录有完善的版本日志,用户可以随时回退到修改过程中的任何一个版本,还能比较差异.这个历史记录功能可以和代码库中的版本控制媲美. 图一:生成历史记录 ...