·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> Android开发 >> 实例讲解Android中SQLiteDatabase使用方法

实例讲解Android中SQLiteDatabase使用方法

作者:佚名      Android开发编辑:admin      更新时间:2022-07-23

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的表。

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