实例讲解Android中SQLiteDatabase使用方法

所属分类: 软件编程 / Android 阅读数: 1442
收藏 0 赞 0 分享

SQLite数据库是android系统内嵌的数据库,小巧强大,能够满足大多数SQL语句的处理工作,而SQLite数据库仅仅是个文件而已。虽然SQLite的有点很多,但并不是如同PC端的mysql般强大,而且android系统中不允许通过JDBC操作远程数据库,所以只能通过webservice等手段于php、servlet交互获取数据。

SQLiteDatabase类,代表了一个数据库对象,通过SQLiteDatabase来操作管理数据库。

一些基本的用法:

  static  SQLiteDatabase openDatabase(String path,SQLiteDatabase.CUrsorFactory factory,int flag);

  static SQLiteDatabase openOrCreateDatabase(File file,SQLiteDatabase.CursorFactory factory);

  static SQLiteDatabase openOrCreateDatabase(String path,SQLiteDatabse.CursorFactory factory);

通过这些静态方法可以很方便的打开和新建一个数据库。

1、execSQL(String sql,Object[] bindArgs)

2、execSQL(String sql)

3、rawQuery(String sql,String[] selectionArgs);

4、beginTransaction()

5、endTransaction()

这些函数可以完成SQL功能,对于查询出来的结果是用Cursor表示的,类似于JDBC中的ResultSet类,在这些类中通过方法move(int offset)、moveToFirst()、moveToLast()、moveToNext()、moveToPosition(int position)、moveToPrivious()获取需要的结果行。

下面通过一个实例来说明一下SQLiteDatabase的基本使用

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:orientation="vertical"
  tools:context=".Main" >

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:gravity="center"
      android:text="key" />

    <EditText
      android:id="@+id/keys"
      android:layout_width="100sp"
      android:layout_height="wrap_content" />

    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:gravity="center"
      android:text="value" />

    <EditText
      android:id="@+id/values"
      android:layout_width="100sp"
      android:layout_height="wrap_content" />

    <Button
      android:id="@+id/btn"
      android:layout_width="100sp"
      android:layout_height="wrap_content"
      android:text="submit" />
  </LinearLayout>

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ListView
      android:id="@+id/lv"
      android:layout_width="match_parent"
      android:layout_height="wrap_content" />
  </LinearLayout>

</LinearLayout>

用于填充数据的mytextview.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="wrap_content"
  android:orientation="horizontal" >

  <TextView
    android:id="@+id/listkey"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="left" />

  <TextView
    android:id="@+id/listvalue"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="300sp" />

</LinearLayout>

Main.java

package com.app.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class Main extends Activity {

  EditText ed1 = null;
  EditText ed2 = null;
  Button btn = null;
  ListView lv = null;
  SQLiteDatabase db = null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ed1 = (EditText) this.findViewById(R.id.keys);
    ed2 = (EditText) this.findViewById(R.id.values);
    btn = (Button) this.findViewById(R.id.btn);
    lv = (ListView) this.findViewById(R.id.lv);

    db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()
        + "/my.db3", null);

    btn.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View view) {

        String key = ed1.getText().toString();

        String value = ed2.getText().toString();

        try {
          insertData(db, key, value);

          Cursor cursor = db.rawQuery("select * from tb_info", null);

          inflateListView(cursor);

        } catch (Exception e) {

          String sql = "create table tb_info(_id integer primary key autoincrement,db_key varchar(20),db_value varchar(50))";

          db.execSQL(sql);

          insertData(db, key, value);

          Cursor cursor = db.rawQuery("select * from tb_info", null);

          inflateListView(cursor);
        }

      }

    });

  }

  // 向数据库中插入数据
  private void insertData(SQLiteDatabase db, String key, String value) {
    db.execSQL("insert into tb_info values (null,?,?)", new String[] { key,
        value });
    System.out.println("------------------");
  }

  // 向ListView中填充数据
  @SuppressLint("NewApi")
  public void inflateListView(Cursor cursor) {

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(Main.this,
        R.layout.mytextview, cursor, new String[] { "db_key",
            "db_value" },
        new int[] { R.id.listkey, R.id.listvalue },
        CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

    lv.setAdapter(adapter);

  }

  @Override
  protected void onDestroy() {

    super.onDestroy();
    if (db != null && db.isOpen()) {
      db.close();
    }
  }

}

实现的效果:

需要特别指出,在用SimpleCursorAdapter封装Cursor的时候,要求底层数据库表的主键列的列名为_id,因为SimpleCursorAdapter只能识别主键列名为_id的表。

以上就是本文的全部内容,希望能给大家一个参考,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Android中加入名片扫描功能实例代码

这篇文章主要介绍了Android中加入名片扫描功能实例代码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

Android仿微信发表说说实现拍照、多图上传功能

这篇文章主要为大家详细介绍了Android仿微信发表说说实现拍照、多图上传功能,使用Retrofit2.0技术,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

设置Android系统永不锁屏永不休眠的方法

在进行Android系统开发的时候,有些特定的情况需要设置系统永不锁屏,永不休眠。本篇文章给大家介绍Android 永不锁屏,开机不锁屏,删除设置中休眠时间选项,需要的朋友一起学习吧
收藏 0 赞 0 分享

Android Retrofit 2.0框架上传图片解决方案

这篇文章主要介绍了Android Retrofit 2.0框架上传一张与多张图片解决方案,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android自定义等待对话框

这篇文章主要为大家详细介绍了Android自定义等待对话框的实现方法,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Android中Window添加View的底层原理

这篇文章主要介绍了Android中Window添加View的底层原理,需要的朋友可以参考下
收藏 0 赞 0 分享

Android调用系统默认浏览器访问的方法

这篇文章主要介绍了Android调用系统默认浏览器访问的方法的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

Android开发退出程序的方法汇总

Android程序有很多Activity,比如说主窗口A,调用了子窗口B,子窗口B又调用子窗口C,back返回子窗口B后,在B中如何关闭整个Android应用程序呢? 下面脚本之家小编就给大家介绍android开发退出程序的几种方法,感兴趣的朋友参考下吧
收藏 0 赞 0 分享

Android程序开发中单选按钮(RadioGroup)的使用详解

在android程序开发中,无论是单选按钮还是多选按钮都非常的常见,接下来通过本文给大家介绍Android程序开发中单选按钮(RadioGroup)的使用,需要的朋友参考下吧
收藏 0 赞 0 分享

Android实现仿网易今日头条等自定义频道listview 或者grideview等item上移到另一个view中

这篇文章主要介绍了Android实现仿网易今日头条等自定义频道listview 或者grideview等item上移到另一个view中 的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多