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

Android——使用SQLite数据库访问

2014-12-16 16:15 302 查看
http://z18022893621.iteye.com/blog/1965226

SQLite,是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如
Tcl、C#、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源世界著名的数据库管理系统来讲,它的处理速度比他们都快。SQLite第一个Alpha版本诞生于2000年5月。至今已经有12个年头,SQLite也迎来了一个版本
SQLite 3已经发布。

一、界面



二、程序包结构



三、layout中包含2给配置文件,main.xml(里面包含一个ListView控件)和person.xml(与ListView对应的TextView)
main.xml

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" >

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

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="编号"
android:textSize="18sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="姓名"
android:textSize="18sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="年龄"
android:textSize="18sp" />
</LinearLayout>

<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

</LinearLayout>

person.xml

Xml代码


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/id"
android:layout_width="120px"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="3dip"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/name"
android:layout_width="180px"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_margin="3dip"
android:layout_toRightOf="@+id/id"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/age"
android:layout_width="50px"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_margin="3dip"
android:layout_toRightOf="@+id/name"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

四、AndroidManifest.xml,配置了Android单元测试

Xml代码


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.e276.db"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >

<!-- Android配置单元测试 -->
<uses-library android:name="android.test.runner" />

<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

<!-- Android配置单元测试 -->
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="org.e276.db" />

</manifest>

五、entity

Java代码


package org.e276.entity;

/**
* 实体类
*
* @author miao
*
*/
public class Person {

private Integer id;
private String name;
private Integer age;

public Person() {
super();
}

public Person(Integer id, String name, Integer age) {
super();
this.id = id;
this.name = name;
this.age = age;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}

}

六、dao,带一dao辅助类
DBHelper.java

Java代码


package org.e276.dao;

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

/**
* 数据库辅助类
*
* @author miao
*
*/
public class DBHelper extends SQLiteOpenHelper {

/*
* @param context 上下文
*
* @param name 数据库名字
*
* @param factory 游标工厂对象,没指定就设置为null
*
* @param version 版本号
*/
// public DBHelper(Context context, String name, CursorFactory factory,
// int version) {
// super(context, name, factory, version);
// }

private static final String DB_NAME = "ali.db";
private static final int VERSION = 1;

public DBHelper(Context context) {
super(context, DB_NAME, null, VERSION);
}

/**
* 第一次运行的时候创建
*/
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS person (personid integer primary key autoincrement, name text, age INTEGER)");
}

/**
* 更新的时候
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS person");
onCreate(db);
}

}

PersonDao.java

Java代码


package org.e276.dao;

import java.util.ArrayList;
import java.util.List;
import org.e276.entity.Person;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* 实现类
* @author miao
*
*/
public class PersonDao {

// 辅助类属性
private DBHelper helper;

/**
* 带参构造方法,传入context
*
* @param context
*/
public PersonDao(Context context) {
helper = new DBHelper(context);
}

/**
* 使用不同的方法删除记录1到多条记录
*
* @param ids
*/
public void delete(Integer... ids) {
String[] c = new String[ids.length];
StringBuffer sb = new StringBuffer();
if (ids.length > 0) {
for (int i = 0; i < ids.length; i++) {
sb.append('?').append(',');
// 把整数数组转换哼字符串数组
c[i] = ids[i].toString();
}
// 删除最后一个元素
sb.deleteCharAt(sb.length() - 1);
}
SQLiteDatabase db = helper.getWritableDatabase();
db.delete("person", "personid in (" + sb.toString() + ")", c);
db.close();
}

/**
* 添加纪录
*
* @param person
*/
public void save(Person person) {
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("insert into person (name,age) values(?,?)", new Object[] {
person.getName(), person.getAge() });
db.close();
}

/**
* 根据id查找
*
* @param id
* @return
*/
public Person find(Integer id) {
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from person where personid=?",
new String[] { String.valueOf(id) });
if (cursor.moveToNext()) {
return new Person(cursor.getInt(0), cursor.getString(1),
cursor.getInt(2));
}
return null;
}

/**
* 查找所有的记录
*
* @return
*/
public List<Person> getAll() {
List<Person> persons = new ArrayList<Person>();
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from person", null);
while (cursor.moveToNext()) {
persons.add(new Person(cursor.getInt(0), cursor.getString(1),
cursor.getInt(2)));
}
return persons;
}

/**
* 查询全部
*
* @return 游标
*/
public Cursor getAllPerson() {
SQLiteDatabase db = helper.getReadableDatabase();
// ListView 里的id是有个下划线的,所以这里要给个别名_id
Cursor cursor = db.rawQuery(
"select personid as _id, name,age from person", null);
// 这里数据库不能关闭
return cursor;
}

}

六、Activity类

Java代码


package org.e276.db;

import org.e276.dao.PersonDao;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {

// 声明ListView对象
private ListView listView;

// Dao
private PersonDao personDao;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// 获得listview
listView = (ListView) findViewById(R.id.listView);
// 实例化dao
personDao = new PersonDao(this);
// 得到所有的记录
Cursor cursor = personDao.getAllPerson();

/*
* 参数作用:context:显示数据的layout,游标:显示的列名(一定要包含_id),显示的控件id名
*/
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.person, cursor, new String[] { "_id", "name", "age" },
new int[] { R.id.id, R.id.name, R.id.age });
listView.setAdapter(adapter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ListView lst = (ListView) parent;
// 得到其中的一行
SQLiteCursor cursor = (SQLiteCursor) lst
.getItemAtPosition(position);
Toast.makeText(MainActivity.this, cursor.getString(1) + "被选中",
Toast.LENGTH_SHORT).show();
}
});
}

}

七、test类,导入JUnit3包

Java代码


package org.e276.test;

import java.util.List;
import java.util.Random;
import org.e276.dao.PersonDao;
import org.e276.entity.Person;
import android.database.Cursor;
import android.test.AndroidTestCase;
import android.util.Log;

/**
* 测试类 用的是JUnit3,用4可能会报错
*
* @author miao
*
*/
public class TestPersonDao extends AndroidTestCase {

PersonDao personDao = new PersonDao(getContext());

@Override
protected void setUp() throws Exception {
personDao = new PersonDao(getContext());
}

/**
* 保存
*/
public void testSave() {
for (int i = 1; i <= 30; i++) {
personDao.save(new Person(-1, "用户" + i, new Random().nextInt(100)));
}
}

/**
* 根据id查找
*/
public void testFind() {
Person person = personDao.find(1);
Log.i("tag", person.toString());
}

/**
* 查找全部 集合
*/
public void testFindAll() {
List<Person> persons = personDao.getAll();
for (Person person : persons) {
Log.i("tag", person.toString());
}
}

/*
* 使用命令行查看内嵌数据库 在DOS下输入adb shell,或在sdk下的adb.exe下输入该命令
*
* Sqliteman 这个工具,可以打开db文件
*/

/**
* 查找全部 游标
*/
public void testGetAll() {
Cursor cursor = personDao.getAllPerson();
while (cursor.moveToNext()) {
StringBuffer sb = new StringBuffer();
sb.append("ID:" + cursor.getInt(0));
sb.append("\t用户名:" + cursor.getString(1));
sb.append("\t年龄:" + cursor.getInt(2));
Log.i("person", sb.toString());
}
}

/**
* 测试删除多条记录
*/
public void testDelete(){
personDao.delete(2,5,9);
}

}

测试时,先运行save方法,向数据库循环添加纪录



运行其他方法时,例如testFind(),可以在LogCat里查看得到,前提是添加过滤器。

八、查看添加了的数据,可以运行app直接查看,又可以在dos控制台下输入命令查看
使用dir命令查看目录结构,然后用cd 目录名进入该目录,直到找到sdk里面的adb.exe为止。
接着使用adb shell命令,打开,出现“#”号代表已经打开了该程序。
ls 代表查看目录。
.help代表查看帮助命令,.tables代表查看数据库的表。
出现sqlite的时候代表可以使用SQL查询语句,增删改都会对数据库产生作用。

命令参考图,来自度娘



查询的结果(控制台中出现乱码是正常的,并不影响真正的查询结果):



九、demo
Android-DB.zip

Android-DB.zip (227.4 KB)
下载次数: 87

查看图片附件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐