首页 > 代码库 > Android SQLite简介

Android SQLite简介

  SQLite 一个非常流行的嵌入式数据库,它支持 SQL 语言,并且只利用很少的内存就有很好的性能。此外它还是开源的,任何人都可以使用它。许多开源项目((Mozilla, PHP, Python)都使用了 SQLite;

  Android 不自动提供数据库。在 Android 应用程序中使用 SQLite,必须自己创建数据库,然后创建表、索引,往里面添加数据。Android 提供了 SQLiteOpenHelper 帮助你创建一个数据库,你只要继承 SQLiteOpenHelper 类,就可以轻松的创建数据库。SQLiteOpenHelper 类根据开发应用程序的需要,封装了创建和更新数据库使用的逻辑。SQLiteOpenHelper 的子类,至少需要实现三个方法:

  • 构造函数,调用父类 SQLiteOpenHelper 的构造函数。这个方法需要四个参数:上下文环境(例如,一个 Activity),数据库名字,一个可选的游标工厂(通常是 Null),一个代表你正在使用的数据库模型版本的整数。
  • onCreate()方法,它需要一个 SQLiteDatabase 对象作为参数,根据需要对这个对象填充表和初始化数据。
  • onUpgrage() 方法,它需要三个参数,一个 SQLiteDatabase 对象,一个旧的版本号和一个新的版本号,这样你就可以清楚如何把一个数据库从旧的模型转变到新的模型。

详细介绍可以参考:

http://www.cnblogs.com/Excellent/archive/2011/11/19/2254888.html

http://blog.csdn.net/liuhe688/article/details/6715983

 

下面以一个增删改查的简单例子来说明一下:具体如图:

点击添加数据,然后点击查询数据:

 

然后点击修改,然后再查询:

 

然后删除,再查询:

 

实现代码如下:

MainActivity.java

package com.xiaozhang.sqltest1;import java.util.ArrayList;import java.util.HashMap;import java.util.Map;import android.app.Activity;import android.content.ContentValues;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.view.View;import android.widget.ListView;import android.widget.SimpleAdapter;public class MainActivity extends Activity {    private DatabaseHelper databaseHelper;    private SQLiteDatabase sqlite;    private ListView listView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        listView = (ListView) findViewById(R.id.listView);        databaseHelper = new DatabaseHelper(this);        sqlite = databaseHelper.getWritableDatabase();    }    // 添加Student信息    public void add(View view) {        ArrayList<Student> student = new ArrayList<Student>();        Student student1 = new Student("张三", 23, "河南省");        Student student2 = new Student("李四", 25, "山东省");        Student student3 = new Student("王五", 21, "陕西省");        Student student4 = new Student("赵六", 22, "福建省");        student.add(student1);        student.add(student2);        student.add(student3);        student.add(student4);        // 设置事务        sqlite.beginTransaction(); // 开始事务        try {            for (Student stu : student) {                sqlite.execSQL("INSERT INTO student VALUES(null, ?, ?, ?)",                        new Object[] { stu.name, stu.age, stu.address });            }            sqlite.setTransactionSuccessful(); // 设置事务成功完成        } finally {            sqlite.endTransaction(); // 结束事务        }    }    // 将姓名为  "张三" 的地址修改为 "北京市";    public void update(View view) {        ContentValues cv = new ContentValues();        Student student = new Student();        student.address = "北京市";        student.name = "张三";        cv.put("address", student.address);        sqlite.update("student", cv, "name = ?", new String[] { student.name });    }    // 删除年龄为22岁的人    public void delete(View view) {        Student student = new Student();        student = new Student();        student.age = 22;        sqlite.delete("student", "age = ?",                new String[] { String.valueOf(student.age) });    }    //查询全部信息    public void query(View view) {        Student student = new Student();        Cursor c = sqlite.rawQuery("SELECT * FROM student", null);        ArrayList<Student> list = new ArrayList<Student>();        while (c.moveToNext()) {            student = new Student();            student._id = c.getInt(c.getColumnIndex("_id"));            student.name = c.getString(c.getColumnIndex("name"));            student.address = c.getString(c.getColumnIndex("address"));            student.age = c.getInt(c.getColumnIndex("age"));            list.add(student);        }        ArrayList<Map<String, String>> list2 = new ArrayList<Map<String, String>>();        for (Student stu : list) {            HashMap<String, String> map = new HashMap<String, String>();            map.put("name", stu.name);            map.put("address", "-----"+stu.address + "-----" + stu.age + " years old");            list2.add(map);        }        c.close();        SimpleAdapter adapter = new SimpleAdapter(this, list2,                android.R.layout.simple_list_item_2, new String[] { "name",                        "address" }, new int[] { android.R.id.text1,                        android.R.id.text2 });        listView.setAdapter(adapter);    }}

 

DatabaseHelper.java

package com.xiaozhang.sqltest1;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class DatabaseHelper extends SQLiteOpenHelper {    private static final String DATABASE_NAME = "study";    private static final int DATABASE_VERSION = 1;    public DatabaseHelper(Context context) {        super(context, DATABASE_NAME, null, DATABASE_VERSION);    }    @Override    public void onCreate(SQLiteDatabase db) {        db.execSQL("CREATE TABLE IF NOT EXISTS student"                + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age INTEGER, address TEXT)");    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        db.execSQL("ALTER TABLE student ADD COLUMN other STRING");    }}

 

activity_main.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" >    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="add"        android:text="添加数据" />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="update"        android:text="更新数据" />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="delete"        android:text="删除数据" />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="query"        android:text="查询数据" />    <ListView        android:id="@+id/listView"        android:layout_width="match_parent"        android:layout_height="wrap_content" /></LinearLayout>

 

如有需要,可以下载代码:http://download.csdn.net/detail/u012724379/8239741

 

Android SQLite简介