当前位置: 移动技术网 > 移动技术>移动开发>Android > 详解Android轻量型数据库SQLite

详解Android轻量型数据库SQLite

2019年07月24日  | 移动技术网移动技术  | 我要评论

数据库是android存储方案的核心,在andorid中sqlite非常轻量,而且执行sql语句甚至比mysql还要快。
sqlitedatabase 是 android 中操作数据库的核心类之一,使用sqlitedatabase可以打开数据库,也可以对数据库进行操作,然而,为了数据库升级以及使用更加方便,我们常用sqliteopenhelper的子类来完成创建,打开数据库的操作。
sqliteopenhelper是一个抽象类,在该类中有下面两个必须实现的方法:

public void oncreate(sqlitedatabase db);// 该函数在数据库第一次被建立时调用
public void onupgrade(sqlitedatabase db,int oldversion,int newversion);// 数据库更新升级操作

我们新建一个类dbhelper extends sqliteopenhelper

import java.util.random;

import android.r.bool;
import android.content.context;
import android.database.cursor;
import android.database.sqlite.sqlitedatabase;
import android.database.sqlite.sqlitedatabase.cursorfactory;
import android.database.sqlite.sqliteopenhelper;

public class dbhelper extends sqliteopenhelper {

 // 设置数据库默认版本
 private static final int verson = 1;
 // 自定义数据库名,可以随便取名字
 private static final string dbname = "mydb";

 // 继承sqliteopenhelper类的类必须有自己的构造函数
 // 该构造函数4个参数,直接调用父类的构造函数。其中第一个参数为该类本身;第二个参数为数据库的名字;
 public dbhelper(context context, string name, cursorfactory factory,
   int version) {
  super(context, name, factory, version);
 }

 // 该构造函数有3个参数,因为它把上面函数的第3个参数固定为null了
 public dbhelper(context context, string name, int verson) {
  this(context, name, null, verson);
 }

 // 该构造函数只有2个参数,在上面函数 的基础上将版本号固定了
 public dbhelper(context context, string name) {
  this(context, name, verson);
 }

 // 该构造函数只有1个参数,固定默认数据库,在这里我们实现增删改查为了方便,就用它了
 public dbhelper(context context) {
  this(context, dbname, null, verson);
 }

 // 该函数在数据库第一次被建立时调用
 public void oncreate(sqlitedatabase db) {
  system.out.println("create a sqlite database");
  //建表语句(注意:因为在绑定数据时,cursor对象返回的记录集中必须包含一个"_id"字段,否则无法完成数据绑定
  string sql = "create table [test]("+
      "[_id] autoinc,"+
      "[name] varchar(20),"+
      "[age] varchar(20),"+
      "primary key ([_id]))";
  db.execsql(sql);

  //向test表中插入10条数据
  for (int i = 1; i <= 10; i++) {
   string name = "jepson";
   name+=i;
   string age = "age";
   age+=i;
   db.execsql("insert into test(name,age) values(?,?)",new object[]{name,age});
  }
 }

 // 数据库更新操作
 public void onupgrade(sqlitedatabase arg0, int arg1, int arg2) {
  system.out.println("update a sqlite database");
 }

 //自定义query方法,用以执行查询语句,返回cursor对象
 public cursor query(string sql,string[] args){
  //调用 getreadabledatabase方法时,如果数据库文件不存在,会调用 oncreate方法
  sqlitedatabase db = this.getreadabledatabase();
  cursor cursor = db.rawquery(sql, args);
  return cursor;
 }
}

这样,我们的dbhelper 类写好了,我们来实现一个查询操作。

第一步,activity_main.xml添加 listview 展示控件

activity_main.xml

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#ffffff"
 android:orientation="vertical"
 tools:context=".mainactivity" >

 <listview
  android:id="@android:id/list"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_weight="1"
  android:divider="#6b6f74"
  android:dividerheight="1px" >
 </listview>

</linearlayout>

第二步,新建一个xml布局文件,用来作为列表项使用的布局资源

user_list_cell.xml

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical" 
 android:background="#ffffff">
 <!-- 大字体textview,用以展示 name姓名 -->
 <textview
  android:id="@+id/tvname"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="large"
  android:textcolor="#000000"
  android:textsize="20dp" />

 <!-- 小字体textview,用以展示 age年龄 -->
 <textview
  android:id="@+id/tvage"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="small"
  android:textcolor="#000000"
  android:textsize="14dp" />

</linearlayout>

第三步,主activity

import android.os.bundle;
import android.app.activity;
import android.app.listactivity;
import android.database.cursor;
import android.support.v4.widget.simplecursoradapter;
import android.view.menu;
import android.widget.toast;

public class mainactivity extends listactivity {

 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
  initview();
 }

 public void initview(){
  //调用只有1个参数的构造函数,实例化dbhelper
  dbhelper dbhelper = new dbhelper(this);
  //新建cursor对象来保存query查询方法返回的结果,查询test表中所有记录
  cursor cursor = dbhelper.query("select * from test", null);
  //创建simplecursoradapter对象,5个参数,
  //第一个是context,就写当前this就行
  //第二个是布局文件,我这里是自定义的布局文件user_list_cell.xml
  //第三个就是cursor对象
  //第四个对应就是,cursor查询后,需要显示出来的字段名,比如我要显示姓名name和年龄age
  //第五个就是对应列表项布局中的控件id了
  simplecursoradapter simplecursoradapter = new simplecursoradapter(this,
    r.layout.user_list_cell, cursor,
    new string[] { "name", "age" }, new int[] { r.id.tvname,
      r.id.tvage });
  setlistadapter(simplecursoradapter);
  toast.maketext(this, "查询成功", toast.length_short).show();
 }
}

执行一下看看,我们是不是查询成功了?

操作sqlite数据库应了解,对数据库的增删改查都有两种方法,一种是前面的使用 rawquery方法直接执行sql语句,另一种就是使用sqlitedatabase类的相应方法来操作,下面举一个第二种的例子,比如我们要插入数据 name=11 age=22

import android.os.bundle;
import android.app.activity;
import android.app.listactivity;
import android.database.cursor;
import android.support.v4.widget.simplecursoradapter;
import android.view.menu;
import android.widget.toast;

public class mainactivity extends listactivity {

 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
  initview();
 }

 public void initview(){
  //执行添加操作
  dbhelper dbhelper = new dbhelper(this);
  //获得写入权限getwritabledatabase
  sqlitedatabase db = dbhelper.getwritabledatabase();
  //新建contentvalues保存insert数据
  contentvalues cv = new contentvalues();
  cv.put("name", "11");
  cv.put("age", "22");
  db.insert("test", null, cv);
  toast.maketext(this, "添加成功", toast.length_short).show();

  ////查询操作
  ////调用只有1个参数的构造函数,实例化dbhelper
  //dbhelper dbhelper = new dbhelper(this);
  ////新建cursor对象来保存query查询方法返回的结果,查询test表中所有记录
  //cursor cursor = dbhelper.query("select * from test", null);
  ////创建simplecursoradapter对象,5个参数,
  ////第一个是context,就写当前this就行
  ////第二个是布局文件,我这里是自定义的布局文件user_list_cell.xml
  ////第三个就是cursor对象
  ////第四个对应就是,cursor查询后,需要显示出来的字段名,比如我要显示姓名name和年龄age
  ////第五个就是对应列表项布局中的控件id了
  //simplecursoradapter simplecursoradapter = new simplecursoradapter(this,
  //  r.layout.user_list_cell, cursor,
  //  new string[] { "name", "age" }, new int[] { r.id.tvname,
  //    r.id.tvage });
  //setlistadapter(simplecursoradapter);
  //toast.maketext(this, "查询成功", toast.length_short).show();
 }
} 

执行插入成功以后,再将插入语句注释,将查询语句去掉注释,重新启动,会发现最后一多了一个item,添加成功。

另外查询记录获得的cursor对象,需要使用movetofirst,movetonext,movtoposition(position)等方法将指针移动相应的位置,来进行查询结果的读取。

import android.os.bundle;
import android.app.activity;
import android.app.listactivity;
import android.database.cursor;
import android.support.v4.widget.simplecursoradapter;
import android.view.menu;
import android.widget.toast;

public class mainactivity extends listactivity {

 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
  initview();
 }

 public void initview(){
  //解析cursor对象的查询操作
  dbhelper dbhelper = new dbhelper(this);
  sqlitedatabase db = dbhelper.getwritabledatabase();
  cursor cursor = db.query("test", null, null, null, null, null, null,
    null);
  //定义结果字符串
  string result = "";
  // 判断cursor不为空 这个很重要
  if (cursor != null) {
   while (cursor.movetonext()) {
    string name = cursor.getstring(cursor.getcolumnindex("name"));// 获取name列的值
    string age = cursor.getstring(cursor.getcolumnindex("age"));// 获取age列的值
    result += "姓名:" + name + ",年龄:" + age + "\n";
   }
  }
  cursor.close();
  db.close();
  system.out.println(result);
  toast.maketext(this, result, toast.length_short).show();

  // //执行添加操作
  // dbhelper dbhelper = new dbhelper(this);
  // //获得写入权限getwritabledatabase
  // sqlitedatabase db = dbhelper.getwritabledatabase();
  // //新建contentvalues保存insert数据
  // contentvalues cv = new contentvalues();
  // cv.put("name", "11");
  // cv.put("age", "22");
  // db.insert("test", null, cv);
  // toast.maketext(this, "添加成功", toast.length_short).show();

  ////查询操作
  ////调用只有1个参数的构造函数,实例化dbhelper
  //dbhelper dbhelper = new dbhelper(this);
  ////新建cursor对象来保存query查询方法返回的结果,查询test表中所有记录
  //cursor cursor = dbhelper.query("select * from test", null);
  ////创建simplecursoradapter对象,5个参数,
  ////第一个是context,就写当前this就行
  ////第二个是布局文件,我这里是自定义的布局文件user_list_cell.xml
  ////第三个就是cursor对象
  ////第四个对应就是,cursor查询后,需要显示出来的字段名,比如我要显示姓名name和年龄age
  ////第五个就是对应列表项布局中的控件id了
  //simplecursoradapter simplecursoradapter = new simplecursoradapter(this,
  //  r.layout.user_list_cell, cursor,
  //  new string[] { "name", "age" }, new int[] { r.id.tvname,
  //    r.id.tvage });
  //setlistadapter(simplecursoradapter);
  //toast.maketext(this, "查询成功", toast.length_short).show();
 }
} 

执行以后,可以发现,name和age全都获取到了,并显示在了toast和system.out中。是不是很有意思呢?

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网