您的位置:首页 > 移动开发 > Android开发

Android数据存储(六)、SQLite数据库使用实例

2012-08-27 20:37 531 查看
一、首先建立SQLiteOpenHelper的子类。

package com.tao.sqlitedb;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBOpenHelper extends SQLiteOpenHelper{

private static String DB_NAME="test.db";
private static int DB_VERSION=1;
public DBOpenHelper(Context context ) {
super(context, DB_NAME, null,DB_VERSION );
}
//数据库创建的时候调用,去创建一张表
@Override
public void onCreate(SQLiteDatabase db) {
//建张表 3个字段 ,_id为主键 自增长
db.execSQL("create table tbl_person (_id Integer primary key autoincrement,name varchar(20),age Integer)");
}

//数据库版本提升的时候调用,比如软件升级时,要在原本的数据库一个表里面新增加一个字段,或者增加一张表,就在这里面修改数据库
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//
}

}


二、为了体现面向对象的特性,和实现MVC,下面建立一个mode   person

public class Person {
private int _id;
private String name;
private int age;
public Person() {
}
public Person(int _id, String name, int age) {
this._id = _id;
this.name = name;
this.age = age;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
三、实现MVC,封装业务方法,成为Controller

package com.tao.sqlitedb;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBManager {
private DBOpenHelper helper;
private SQLiteDatabase db;

public DBManager(Context context) {
helper = new DBOpenHelper(context);
// 因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0,
// mFactory);
// 所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
db = helper.getWritableDatabase();
}

/**
*
* 添加一条记录
*
* @param person
*/
public void add(Person person) {
db.execSQL("insert into tbl_person values(null,?,?)", new Object[] { person.getName(), person.getAge() });

}

/**
* 添加多条记录
*
* @param persons
*/
public void adds(List<Person> persons) {
db.beginTransaction();
try {
for (Person p : persons) {
db.execSQL("insert into tbl_person values(null,?,?)", new Object[] { p.getName(), p.getAge() });
}
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
db.endTransaction();
}
}

/**
* 更新一条记录
*
* @param person
*/
public void update(Person person) {
db.execSQL("update tbl_person set name=?,age=? where _id=?", new Object[] { person.getName(), person.getAge(), person.get_id() });
}

/**
* 删除一条记录
*
* @param person
*/
public void delete(int id) {
db.execSQL("delete from tbl_person where _id=?", new Object[] { id });
}

/**
* 查询一条记录
*/
public Person queryOne(int _id) {
Person person = new Person();
Cursor c = db.rawQuery("select * from tbl_person where _id=?", new String[] { _id + "" });
while (c.moveToNext()) {
person.set_id(c.getInt(c.getColumnIndex("_id")));
person.setName(c.getString(c.getColumnIndex("name")));
person.setAge(c.getInt(c.getColumnIndex("age")));
}
c.close();
return person;
}

/**
* 查询多条记录
*
* @return List<Person>
*/
public List<Person> queryMany() {
ArrayList<Person> persons = new ArrayList<Person>();
Cursor c = db.rawQuery("select * from tbl_person", null);
while (c.moveToNext()) {
Person person = new Person();
person.set_id(c.getInt(c.getColumnIndex("_id")));
person.setName(c.getString(c.getColumnIndex("name")));
person.setAge(c.getInt(c.getColumnIndex("age")));
persons.add(person);
}
c.close();
return persons;
}

}


四、关于数据库的封装部分已经完成了,那么我们现在就可以简单的使用它了
package com.tao.sqlitedb;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.R.integer;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class SqliteDBActivity extends Activity {
private EditText ed1;
private EditText ed2;
private EditText ed3;
private ListView listView;
private DBManager dbManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dbManager=new DBManager(this);
ed1=(EditText)findViewById(R.id.ed1);
ed2=(EditText)findViewById(R.id.ed2);
ed3=(EditText)findViewById(R.id.ed3);
listView=(ListView)findViewById(R.id.listView);
}
public void add(View view){
Person person=new Person(ed1.getText().toString().trim(), Integer.parseInt(ed2.getText().toString().trim()));
dbManager.add(person);
}

public void delete(View view){
dbManager.delete(Integer.parseInt(ed3.getText().toString().trim()));
}

public void update(View view){
Person person=new Person(Integer.parseInt(ed3.getText().toString().trim()),ed1.getText().toString().trim(), Integer.parseInt(ed2.getText().toString().trim()));
dbManager.update(person);
}

public void queryOne(View view){
Person person=dbManager.queryOne(Integer.parseInt(ed3.getText().toString().trim()));
List<Person> persons=new ArrayList<Person>();
persons.add(person);
setListView(persons);
}

public void queryMany(View view){
List<Person> persons=dbManager.queryMany();
setListView(persons);
}

public void setListView(List<Person> persons){
List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
for(Person p:persons){
Map<String, Object> map=new HashMap<String, Object>();
map.put("id", p.get_id());
map.put("name", p.getName());
map.put("age", p.getAge());
list.add(map);
}
SimpleAdapter adapter=new SimpleAdapter(this, list, R.layout.cell, new String[]{"id","name","age"}, new int[]{R.id.text1,R.id.text2,R.id.text3});
listView.setAdapter(adapter);
}
}


主布局文件 main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<EditText
android:id="@+id/ed1"
android:hint="姓名"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/ed2"
android:hint="年龄"
android:numeric="integer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>

<EditText
android:id="@+id/ed3"
android:hint="id号"
android:numeric="integer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:text="添加"
android:onClick="add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="刪除"
android:onClick="delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="修改"
android:onClick="update"/>
</LinearLayout>

<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:text="查询一条"
android:onClick="queryOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:text="查询多条"
android:onClick="queryMany"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>

<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>

</LinearLayout>

ListView的布局文件 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="horizontal" >
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<TextView
android:id="@+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐