设为首页 收藏本站
查看: 943|回复: 0

[经验分享] Android——使用SQLite数据库访问

[复制链接]

尚未签到

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

 
二、程序包结构
DSC0001.png
 

 
三、layout中包含2给配置文件,main.xml(里面包含一个ListView控件)和person.xml(与ListView对应的TextView)
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" >
<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 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 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

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

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

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 = ids.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类

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包

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方法,向数据库循环添加纪录
DSC0002.png
 
运行其他方法时,例如testFind(),可以在LogCat里查看得到,前提是添加过滤器。
 
 
八、查看添加了的数据,可以运行app直接查看,又可以在dos控制台下输入命令查看
使用dir命令查看目录结构,然后用cd 目录名进入该目录,直到找到sdk里面的adb.exe为止。
接着使用adb shell命令,打开,出现“#”号代表已经打开了该程序。
ls 代表查看目录。
.help代表查看帮助命令,.tables代表查看数据库的表。
出现sqlite的时候代表可以使用SQL查询语句,增删改都会对数据库产生作用。
 
命令参考图,来自度娘
DSC0003.png


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

 
 
九、demo
 Android-DB.zip
 
 
 
 
 
 

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-307538-1-1.html 上篇帖子: 写了一个sqlite自动下载并编译的批处理脚本(windows下) 下篇帖子: 推荐个好东西——嵌入式数据库sqlite
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表