Android数据存储之SQLite
来源:互联网 发布:python multiply 矩阵 编辑:程序博客网 时间:2024/05/17 03:37
一、SQLite简介
在Android平台上,集成了一个嵌入式关系型数据库—SQLite,SQLite3支持 NULL、INTEGER、REAL(浮点数字)、TEXT(字符串文本)和BLOB(二进制对象)数据类型,虽然它支持的类型虽然只有五种,但实际上sqlite3也接受varchar(n)、char(n)、decimal(p,s) 等数据类型,只不过在运算或保存时会转成对应的五种数据类型。 SQLite最大的特点是你可以保存任何类型的数据到任何字段中,无论这列声明的数据类型是什么。例如:可以在Integer字段中存放字符串,或者在布尔型字段中存放浮点数,或者在字符型字段中存放日期型值。 但有一种情况例外:定义为INTEGER PRIMARY KEY的字段只能存储64位整数, 当向这种字段中保存除整数以外的数据时,将会产生错误。另外, SQLite 在解析CREATE TABLE 语句时,会忽略 CREATE TABLE 语句中跟在字段名后面的数据类型信息。
二、SQLite的CURD
Android提供了一个名为SQLiteDatabase的类,该类封装了一些操作数据库的API,使用该类可以完成对数据进行添加(Create)、查询(Retrieve)、更新(Update)和删除(Delete)操作(这些操作简称为CRUD)。对SQLiteDatabase的学习,我们应该重点掌握execSQL()和rawQuery()方法。 execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句; rawQuery()方法可以执行select语句。SQLiteDatabase还专门提供了对应于添加、删除、更新、查询的操作方法: insert()、delete()、update()和query() 。这些方法实际上是给那些不太了解SQL语法的菜鸟使用的,对于熟悉SQL语法的程序员而言,直接使用execSQL()和rawQuery()方法执行SQL语句就能完成数据的添加、删除、更新、查询操作。
三、SQLite的事务管理
使用SQLiteDatabase的beginTransaction()方法可以开启一个事务,程序执行到endTransaction() 方法时会检查事务的标志是否为成功,如果为成功则提交事务,否则回滚事务。当应用需要提交事务,必须在程序执行到endTransaction()方法之前使用setTransactionSuccessful() 方法设置事务的标志为成功,如果不调用setTransactionSuccessful() 方法,默认会回滚事务。
四、SQLite创建、更新数据表
如果应用使用到了SQLite数据库,在用户初次使用软件时,需要创建应用使用到的数据库表结构及添加一些初始化记录,另外在软件升级的时候,也需要对数据表结构进行更新。在Android系统,为我们提供了一个名为SQLiteOpenHelper的类,该类用于对数据库版本进行管理,该类是一个抽象类,必须继承它才能使用。为了实现对数据库版本进行管理,SQLiteOpenHelper类有两种重要的方法,分别是onCreate(SQLiteDatabase db)和onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
当调用SQLiteOpenHelper的getWritableDatabase()或者getReadableDatabase()方法获取用于操作数据库的SQLiteDatabase实例的时候,如果数据库不存在,Android系统会自动生成一个数据库,接着调用onCreate()方法,onCreate()方法在初次生成数据库时才会被调用,在onCreate()方法里可以生成数据库表结构及添加一些应用使用到的初始化数据。onUpgrade()方法在数据库的版本发生变化时会被调用,数据库的版本是由程序员控制的,假设数据库现在的版本是1,由于业务的需要,修改了数据库表的结构,这时候就需要升级软件,升级软件时希望更新用户手机里的数据库表结构,为了实现这一目的,可以把原来的数据库版本设置为2(或其他数值),并且在onUpgrade()方法里面实现表结构的更新。当软件的版本升级次数比较多,这时在onUpgrade()方法里面可以根据原版号和目标版本号进行判断,然后作出相应的表结构及数据更新。
getWritableDatabase()和getReadableDatabase()方法都可以获取一个用于操作数据库的SQLiteDatabase实例。但getWritableDatabase() 方法以读写方式打开数据库,一旦数据库的磁盘空间满了,数据库就只能读而不能写,倘若使用的是getWritableDatabase() 方法就会出错。getReadableDatabase()方法先以读写方式打开数据库,如果数据库的磁盘空间满了,就会打开失败,当打开失败后会继续尝试以只读方式打开数据库。
五、SQLite示例程序
1.实体类Contact
package wei.cao.sqlite.entity;public class Contact { public Integer _id; public String name; public String phone;public Contact(Integer id,String name, String phone) {super();this._id=id;this.name = name;this.phone = phone;}@Overridepublic String toString() {return "Contants[id="+this._id+",name="+this.name+",phone"+this.phone;}}
2.编写MyOpenHelper类
MyOpenHelper继承自SQLiteOpenHelper类。我们需要创建数据表,必须重写onCreate(更新时重写onUpgrade方法)方法,在这个方法中创建数据表。
package wei.cao.sqlite.helper;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class MyOpenHelper extends SQLiteOpenHelper{ //数据库的名字 private static final String dbName="contants"; private static final int version=1; public MyOpenHelper(Context context) {super(context, dbName, null, version);// TODO Auto-generated constructor stub}@Overridepublic void onCreate(SQLiteDatabase arg0) {// TODO Auto-generated method stubarg0.execSQL("create table if not exists " +"contacts(" +"_id integer primary key autoincrement," +"name varchar(20)," +"phone varchar(50))");}@Overridepublic void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {// TODO Auto-generated method stubarg0.execSQL("drop table contacts if exists contacts");this.onCreate(arg0);}}
3.编写ContactsService类
ContactsService类主要实现对业务逻辑和数据库的操作。
package wei.cao.sqlite.service;import android.content.Context;import android.database.Cursor;import wei.cao.sqlite.entity.Contact;import wei.cao.sqlite.helper.MyOpenHelper;public class ContactsService {private MyOpenHelper openHelper;public ContactsService(Context context) {this.openHelper=new MyOpenHelper(context);}/* * 保存 */ public void save(Contact contact) { String sql="insert into contacts(name,phone) values(?,?)"; Object[] bindArgs={contact.name,contact.phone}; this.openHelper.getWritableDatabase().execSQL(sql, bindArgs); }/* * 查找 */ public Contact find(int id) { String sql="select _id,name,phone from contacts where _id=?"; String[] selectionArgs={id+""}; Cursor cursor=this.openHelper.getReadableDatabase().rawQuery(sql, selectionArgs); if(cursor.moveToFirst()) { return new Contact(cursor.getInt(0),cursor.getString(1),cursor.getString(2)); } return null; }/* * 更新 */ public void update(Contact contact) { String sql="update contacts set name=?,phone=? where _id=?"; Object[] bindArgs={contact.name,contact.phone,contact._id}; this.openHelper.getWritableDatabase().execSQL(sql, bindArgs); } /* * 删除 */ public void delete(int id) { String sql="delete from contacts where _id=?"; Object[] bindArgs={id}; this.openHelper.getWritableDatabase().execSQL(sql, bindArgs); } /* * 获取记录数量 */ public long getCount() { String sql="select count(*) from contacts"; Cursor cursor=this.openHelper.getReadableDatabase().rawQuery(sql, null); cursor.moveToFirst(); return cursor.getLong(0); } /* * 获取分页数据,提供SimpleCursorAdapter使用 */ public Cursor getScrollDataCursor(long startIndex,long maxCount) { String sql="select _id,name,phone from contacts limit ?,?"; String[] selectionArgs={String.valueOf(startIndex),String.valueOf(maxCount)}; Cursor cursor=this.openHelper.getReadableDatabase().rawQuery(sql, selectionArgs); return cursor; } }
4.测试ContactsService类中的方法是否正确
try{ ContactsService contactService=new ContactsService(this); Contact obj=new Contact(null,"weicao","1351724671"); contactService.save(obj); obj=new Contact(null,"chaodeng","1357898789"); contactService.save(obj); } catch(Exception e){ e.printStackTrace(); }
5.分页并将数据显示在ListView控件中
我们在ContactsService类中,提供了一个获取分页数据的方法。我们将调用它获取的数据,使用ListView组件显示出来。Android为我们提供了一个SimpleCursorAdapter类
(1)编辑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" > <!-- ListView --> <ListView android:id="@+id/listView" android:layout_width="fill_parent" android:layout_height="fill_parent"></ListView></LinearLayout>
(2)在layout目录下添加contactitem.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" > <!-- coantact:id --> <TextView android:id="@+id/tv_id" android:layout_width="100pt" android:layout_height="wrap_content"></TextView> <!-- coantact:name--> <TextView android:id="@+id/tv_name" android:layout_width="150pt" android:layout_height="wrap_content"></TextView> <!-- coantact:phone --> <TextView android:id="@+id/tv_phone" android:layout_width="100pt" android:layout_height="wrap_content"></TextView></LinearLayout>
(3)编辑Data_SqliteActivity.java
package wei.cao.data;import wei.cao.sqlite.service.ContactsService;import android.app.Activity;import android.database.Cursor;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ListView;import android.widget.SimpleCursorAdapter;import android.widget.Toast;public class Data_SqliteActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //获取分页数据 ContactsService contactService=new ContactsService(this); Cursor cursor=contactService.getScrollDataCursor(0, 3); //获取ListView ListView lv=(ListView)this.findViewById(R.id.listView); //创建Adapter SimpleCursorAdapter adapter=new SimpleCursorAdapter(this, R.layout.contactitem, cursor, new String[]{"_id","name","phone"}, new int[]{R.id.tv_id,R.id.tv_name,R.id.tv_phone}); //设置ListView适配器 lv.setAdapter(adapter); //为ListView添加事件 lv.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position,long id) {Cursor cursor=(Cursor)parent.getItemAtPosition(position);Toast.makeText(Data_SqliteActivity.this, cursor.getString(1), 1).show();}}); }}
(4)执行结果
总结:
(1)int 是基本类型,直接存数值
integer是对象,用一个引用指向这个对象
1.Java 中的数据类型分为基本数据类型和复杂数据类型
int 是前者>>integer 是后者(也就是一个类)
2.初始化时>>
int i =1;
Integer i= new Integer(1);(要把integer 当做一个类看)
int 是基本数据类型(面向过程留下的痕迹,不过是对java的有益补充)
Integer 是一个类,是int的扩展,定义了很多的转换方法类似的还有:float Float;double Double;string String等
(2)关于这一部分,必须注意sqlite的主键命名,由于simpleCursorAdapter的方法只识别_id,所以,当你用到sqlite的simpleCursorAdapter时,必须把数据表的主键命名为_id。否则就会出现java.lang.IllegalArgumentException: column '_id' does not exist错误。
- 【Android】数据存储之SQLite
- android数据存储之SQLite
- Android数据存储之SQLite
- Android数据存储之SQLite
- Android数据存储之SQLite
- Android之SQLite 数据存储
- Android之SQLite 数据存储
- Android 数据存储之SQLite
- Android数据存储之SQLite
- android数据存储之SQLite
- Android 数据存储之 SQLite
- Android数据存储之Sqlite
- Android数据存储之SQLite
- Android:数据存储之SQLite
- Android数据存储之SQLite
- Android数据存储之SQLite
- Android数据存储之SQLite数据库存储
- Android数据存储之SQLite数据库存储
- ASP.net技巧:DataList、Gridview主从表明细显示
- 在构造StringBuffer对象时,指定合适的capacity
- 那些年读过的好书——C程序设计语言
- 初次将一个C文件 拆开写 遇到的 蛋疼问题"multiple definition of" 错误
- String 转化成double(不用Double.parseDouble(str))
- Android数据存储之SQLite
- 设备驱动基础1:设备模型之总线,驱动,设备
- System Volume Information Win7删除(图解)
- linux 初学
- 队列基本操作的实现
- loadrunner——常见函数
- 编程之美——小飞的电梯调度算法
- 第八周任务三
- Linux中的log介绍(四)--klogd与syslogd的交互