使用SQLiteDatabase操
作SQLite数据库
view plaincopy to clipboardprint?
1./*
2.Android提供了一个名为SQLiteDatabase的类,该类封装了一些操作数据库的API,使用该类
可以完成对数据进行添加(Create)、查询(Retrieve)、更新(Update)和删除(Delete)操作(这些操作简称为CRUD)。对SQLiteDatabase的学习,我们应该重点掌握execSQL()和rawQuery()方法。execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句;rawQuery()方法用于执行select语句。
3.execSQL()方法的使用例子:
4.SQLiteDatabase db=....;
5.db.execSQL("insert into person(name,age)values('测试数据',4)");
6.db.close();
7.执行上面SQL语句会往person表中添加进一条记录,在实际应用中,语句中的“测试数据”这些
参数值会由用户输入界面提供,如果把用户输入的内容原样组拼到上面的insert语句,当用户输入的内容含有单引号时,组拼出来的SQL语句就会存在语法错误。要解决这个问题需要对单引号进行转义,也就是把单引号转换成两个单引号。有些时候用户往往还会输入像“&”这些特殊SQL符号,为保证组拼好的SQL语句语法正确,必须对SQL语句中的这些特殊SQL符号都进行转义,显然,对每条SQL语句都做这样的处理工作是比较烦琐的。SQLiteDatabase类提供了一个重载后的execSQL(String sql,Object[]bindArgs)方法,使用这个方法可以解决前面提到的问题,因为这个方法支持使用占位符参数(?)。使用例子如下:
8.SQLiteDatabase db=....;
9.db.execSQL("insert into person(name,age)values(?,?)",new Object[]{"测试数
据",4});
10.db.close();
11.execSQL(String sql,Object[]bindArgs)方法的第一个参数为SQL语句,第二个参数为SQL
语句中占位符参数的值,参数值在数组中的顺序要和占位符的位置对应。
12.*/
view plaincopy to clipboardprint?
1.public class DatabaseHelper extends SQLiteOpenHelper{
2.//类没有实例化,是不能用作父类构造器的参数,必须声明为静态
3.private static final String name="itcast";//数据库名称
4.private static final int version=1;//数据库版本
5.public DatabaseHelper(Context context){
6.//第三个参数CursorFactory指定在执行查询时获得一个游标实例的工厂类,设置为null,代表
使用系统默认的工厂类
7.super(context,name,null,version);
8.}
9.@Override public void onCreate(SQLiteDatabase db){
10.db.execSQL("CREATE TABLE IF NOT EXISTS person(personid intege
r primary key autoincrement,name varchar(20),age INTEGER)");
11.}
12.@Override public void onUpgrade(SQLiteDatabase db,int oldVersion,i
nt newVersion){
13.db.execSQL("ALTER TABLE person ADD phone VARCHAR(12)NULL");
//往表中增加一列
14.//DROP TABLE IF EXISTS person删除表
15.}
16.}
17.//在实际项目开发中,当数据库表结构发生更新时,应该避免用户存放于数//据库中的数据丢
失。
view plaincopy to clipboardprint?
1./*
2.Android提供了一个名为SQLiteDatabase的类,该类封装了一些操作数据库的API,使用该类
可以完成对数据进行添加(Create)、查询(Retrieve)、更新(Update)和删除(Delete)操作(这些操作简称为CRUD)。对SQLiteDatabase的学习,我们应该重点掌握execSQL()和rawQuery()方法。execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句;rawQuery()方法用于执行select语句。
3.execSQL()方法的使用例子:
4.SQLiteDatabase db=....;
5.db.execSQL("insert into person(name,age)values('测试数据',4)");
6.db.close();
7.执行上面SQL语句会往person表中添加进一条记录,在实际应用中,语句中的“测试数据”这些
参数值会由用户输入界面提供,如果把用户输入的内容原样组拼到上面的insert语句,当用户输入的内容含有单引号时,组拼出来的SQL语句就会存在语法错误。要解决这个问题需要对单引号进行转义,也就是把单引号转换成两个单引号。有些时候用户往往还会输入像“&”这些特殊
SQL符号,为保证组拼好的SQL语句语法正确,必须对SQL语句中的这些特殊SQL符号都进行转义,显然,对每条SQL语句都做这样的处理工作是比较烦琐的。SQLiteDatabase类提供了一个重载后的execSQL(String sql,Object[]bindArgs)方法,使用这个方法可以解决前面提到的问题,因为这个方法支持使用占位符参数(?)。使用例子如下:
8.SQLiteDatabase db=....;
9.db.execSQL("insert into person(name,age)values(?,?)",new Object[]{"测试数
据",4});
10.db.close();
11.execSQL(String sql,Object[]bindArgs)方法的第一个参数为SQL语句,第二个参数为SQL
语句中占位符参数的值,参数值在数组中的顺序要和占位符的位置对应。
12.*/
view plaincopy to clipboardprint?
1./*
2.SQLiteDatabase的rawQuery()用于执行select语句,使用例子如下:
SQLiteDatabase db=....;
3.Cursor cursor=db.rawQuery(“select*from person”,null);
4.while(cursor.moveToNext()){
5.int personid=cursor.getInt(0);//获取第一列的值,第一列的索引从0开始
6.String name=cursor.getString(1);//获取第二列的值
7.int age=cursor.getInt(2);//获取第三列的值
8.}
9.cursor.close();
10.db.close();
11.rawQuery()方法的第一个参数为select语句;第二个参数为select语句中占位符参数的值,
如果select语句没有使用占位符,该参数可以设置为null。带占位符参数的select语句使用例子如下:
12.Cursor cursor=db.rawQuery("select*from person where name like?and age=?
",new String[]{"%传智%","4"});
13.Cursor是结果集游标,用于对结果集进行随机访问,如果大家熟悉jdbc,其实Cursor与JDBC
中的ResultSet作用很相似。使用moveToNext()方法可以将游标从当前行移动到下一行,如果已经移过了结果集的最后一行,返回结果为false,否则为true。另外Cursor还有常用的
moveToPrevious()方法(用于将游标从当前行移动到上一行,如果已经移过了结果集的第一行,返回值为false,否则为true)、moveToFirst()方法(用于将游标移动到结果集的第一行,如果结果集为空,返回值为false,否则为true)和moveToLast()方法(用于将游标移动到
结果集的最后一行,如果结果集为空,返回值为false,否则为true)。
14.
15.*/
view plaincopy to clipboardprint?
1./*
2.除了前面给大家介绍的execSQL()和rawQuery()方法,SQLiteDatabase还专门提供了对应于
添加、删除、更新、查询的操作方法:insert()、delete()、update()和query()。这些方法实际上是给那些不太了解SQL语法的菜鸟使用的,对于熟悉SQL语法的程序员而言,直接使用execSQL()和rawQuery()方法执行SQL语句就能完成数据的添加、删除、更新、查询操作。
3.Insert()方法用于添加数据,各个字段的数据使用ContentValues进行存放。ContentValues
类似于MAP,相对于MAP,它提供了存取数据对应的put(String key,Xxx value)和
getAsXxx(String key)方法,key为字段名称,value为字段值,Xxx指的是各种常用的数
据类型,如:String、Integer等。
4.SQLiteDatabase db=databaseHelper.getWritableDatabase();
5.ContentValues values=new ContentValues();
6.values.put("name","测试数据");
7.values.put("age",4);
8.long rowid=db.insert(“person”,null,values);//返回新添记录的行号,与主键id无
关
9.不管第三个参数是否包含数据,执行Insert()方法必然会添加一条记录,如果第三个参数为空,
会添加一条除主键之外其他字段值为Null的记录。Insert()方法内部实际上通过构造
insert SQL语句完成数据的添加,Insert()方法的第二个参数用于指定空值字段的名称,相信大家对该参数会感到疑惑,该参数的作用是什么?是这样的:如果第三个参数values为Null
或者元素个数为0,由于Insert()方法要求必须添加一条除了主键之外其它字段为Null值的
记录,为了满足SQL语法的需要,insert语句必须给定一个字段名,如:
insert into person(name)values(NULL),倘若不给定字段名,insert语句就成了这
样:insert into person()values(),显然这不满足标准SQL的语法。对于字段名,建议使用主键之外的字段,如果使用了INTEGER类型的主键字段,执行类似
insert into person(personid)values(NULL)的insert语句后,该主键字段值也不会为
NULL。如果第三个参数values不为Null并且元素的个数大于0,可以把第二个参数设置为
null。
10.*/
view plaincopy to clipboardprint?
1./*
2.delete()方法的使用:
3.SQLiteDatabase db=databaseHelper.getWritableDatabase();
4.db.delete("person","personid",new String[]{"2"});
5.db.close();
6.上面代码用于从person表中删除personid小于2的记录。
7.update()方法的使用:
8.SQLiteDatabase db=databaseHelper.getWritableDatabase();
9.ContentValues values=new ContentValues();
10.values.put(“name”,“测试数据”);//key为字段名,value为值
11.db.update("person",values,"personid=?",new String[]{"1"});
12.db.close();
13.上面代码用于把person表中personid等于1的记录的name字段的值改为“测试数据”。
14.
15.*/
view plaincopy to clipboardprint?
1./*
2.query()方法实际上是把select语句拆分成了若干个组成部分,然后作为方法的输入参数:
3.SQLiteDatabase db=databaseHelper.getWritableDatabase();
4.Cursor cursor=db.query("person",new String[]{"personid,name,age"},"name
like?",new String[]{"%传智%"},null,null,"personid desc","1,2");
5.while(cursor.moveToNext()){
6.int personid=cursor.getInt(0);//获取第一列的值,第一列的索引从0开始
7.String name=cursor.getString(1);//获取第二列的值
8.int age=cursor.getInt(2);//获取第三列的值
9.}
10.cursor.close();
11.db.close();
12.上面代码用于从person表中查找name字段含有“传智”的记录,匹配的记录按personid降序排
序,对排序后的结果略过第一条记录,只获取2条记录。
13.query(table,columns,selection,selectionArgs,groupBy,having,orderBy,li
mit)方法各参数的含义:
14.table:表名。相当于select语句from关键字后面的部分。如果是多表联合查询,可以用逗号
将两个表名分开。
15.columns:要查询出来的列名。相当于select语句select关键字后面的部分。
16.selection:查询条件子句,相当于select语句where关键字后面的部分,在条件子句允许使
用占位符“?”
17.selectionArgs:对应于selection语句中占位符的值,值在数组中的位置与占位符在语句中的
位置必须一致,否则就会有异常。
18.groupBy:相当于select语句group by关键字后面的部分
19.having:相当于select语句having关键字后面的部分
20.orderBy:相当于select语句order by关键字后面的部分,如:personid desc,age asc;
21.limit:指定偏移量和获取的记录数,相当于select语句limit关键字后面的部分。
22.*/
view plaincopy to clipboardprint?
1.package com.zyq.db;
2.import android.app.Activity;
3.import android.os.Bundle;
4.public class MainActivity extends Activity
5.{
6.@Override
7.public void onCreate(Bundle savedInstanceState)
8.{
9.super.onCreate(savedInstanceState);
10.setContentView(https://www.wendangku.net/doc/927321740.html,yout.main);
11.}
12.}
view plaincopy to clipboardprint?
1.package com.zyq.db;
2.import java.util.List;
3.import android.test.AndroidTestCase;
4.import android.util.Log;
5.import com.zyq.service.DBOpenHelper;
6.import com.zyq.service.PersonService;
7.import com.zyq.voo.Person;
8.
9./**
10.*测试方法通过Junit单元测试
11.*1.>实例化测试类
12.*2.>把与应用有关的上下文信息传入到测试类实例
13.*3.>运行测试方法
14.*@author Administrator
15.*
16.*/
17.public class PersonServiceTest extends AndroidTestCase
18.{
19.private final static String TAG="PersonServiceTest";
20.
21./**
22.*测试创建数据库
23.*@throws Throwable
24.*/
25.public void testCreateDB()throws Throwable
26.{
27.DBOpenHelper dbOpenHelper=new DBOpenHelper(this.getContext());
28.dbOpenHelper.getReadableDatabase();//Create and/or open a database.
29.}
30./**
31.*测试新增一条记录
32.*@throws Throwable
33.*/
34.public void testSave()throws Throwable
35.{
36.PersonService personService=new PersonService(this.getContext());
37.personService.save(new Person("zhangsan","1360215320"));
38.personService.save(new Person("lisi","1123"));
39.personService.save(new Person("lili","232"));
40.personService.save(new Person("wangda","123123"));
41.personService.save(new Person("laozhu","234532"));
42.}
43./**
44.*查找一条记录
45.*@throws Throwable
46.*/
47.public void testFind()throws Throwable
48.{
49.PersonService personService=new PersonService(this.getContext());
50.Person person=personService.find(1);
51.Log.i(TAG,person.toString());
52.}
53./**
54.*测试更新一条记录
55.*@throws Throwable
56.*/
57.public void testUpdate()throws Throwable
58.{
59.PersonService personService=new PersonService(this.getContext());
60.Person person=personService.find(1);
61.person.setName("lisi");
62.personService.update(person);
63.}
64./**
65.*测试得到所有记录数
66.*@throws Throwable
67.*/
68.public void testGetCount()throws Throwable
69.{
70.PersonService personService=new PersonService(this.getContext());
71.Log.i(TAG,personService.getCount()+"********");
72.}
73./**
74.*测试分页
75.*@throws Throwable
76.*/
77.public void testScroll()throws Throwable
78.{
79.PersonService personService=new PersonService(this.getContext());
80.List
81.for(Person person:persons)
82.{
83.Log.i(TAG,person.toString());
84.}
85.}
86./**
87.*测试删除一条记录
88.*@throws Throwable
89.*/
90.public void testDelete()throws Throwable
91.{
92.PersonService personService=new PersonService(this.getContext());
93.personService.delete(5);
94.}
95.}
view plaincopy to clipboardprint?
1.package com.zyq.service;
2.import android.content.Context;
3.import android.database.sqlite.SQLiteDatabase;
4.import android.database.sqlite.SQLiteOpenHelper;
5.public class DBOpenHelper extends SQLiteOpenHelper
6.{
7./**
8.*如果想额外的增加一个字段(需求)
9.*可以把版本号更改掉但必须>=1
10.*更改版本号之后会根据版本号判断是不是上次创建的时候(目前的版本号和传入的版
本号是否一致)
11.*如果不是会执行onUpgrade()方法
12.*@param context
13.*/
14.public DBOpenHelper(Context context)
15.{
16.super(context,"zyq.db",null,2);
17.}
18./**
19.*在数据库创建的时候第一个调用的方法
20.*适合创建表结构
21.*/
22.@Override
23.public void onCreate(SQLiteDatabase db)
24.{
25.db.execSQL("CREATE TABLE person(personid integer primary key autoin
crement,name varchar(20))");//创建表
26.}
27./**
28.*更新表结构在数据库版本号发生改变的时候调用
29.*应用升级
30.*/
31.@Override
32.public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)
33.{
34.db.execSQL("ALTER TABLE person ADD phone VARCHAR(12)NULL");//往表
中增加一列
35.}
36.}
view plaincopy to clipboardprint?
1.
2. 3.package="com.zyq.db" 4.android:versionCode="1" 5.android:versionName="1.0"> 6. 7. 8. 9.android:label="@string/app_name"> 10. 11. 12. 13. 14. 15. 16. 17. 18.android:targetPackage="com.zyq.db"android:label="Tests for My App" /> 19.
view plaincopy to clipboardprint?
1.package com.zyq.service;
2.import java.util.ArrayList;
3.import java.util.List;
4.import android.content.Context;
5.import android.database.Cursor;
6.import android.database.sqlite.SQLiteDatabase;
7.import com.zyq.voo.Person;
8.public class PersonService
9.{
10.private DBOpenHelper helper;
11.public PersonService(Context context)
12.{
13.helper=new DBOpenHelper(context);
14.}
15./**
16.*新增一条记录
17.*@param person
18.*/
19.public void save(Person person)
20.{
21.SQLiteDatabase db=helper.getWritableDatabase();//Create and/or open
a database that will be used for reading and writing
22.db.execSQL("INSERT INTO person(name,phone)values(?,?)",new Object[]
{person.getName().trim(),person.getPhone().trim()});//使用占位符进行转译
23.//db.close();不关数据库连接。可以提高性能因为创建数据库的时候的操作模式
是私有的。
24.//代表此数据库,只能被本应用所访问单用户
的,可以维持长久的链接
25.}
26./**
27.*更新某一条记录
28.*@param person
29.*/
30.public void update(Person person)
31.{
32.SQLiteDatabase db=helper.getWritableDatabase();
33.db.execSQL("update person set phone=?,name=?where personid=?",
34.new Object[]{person.getPhone().trim(),person.getName().t
rim(),person.getId()});
35.}
36./**
37.*根据ID查询某条记录
38.*@param id
39.*@return
40.*/
41.public Person find(Integer id)
42.{
43.SQLiteDatabase db=helper.getReadableDatabase();
44.Cursor cursor=db.rawQuery("select*from person where personid=?",n
ew String[]{id.toString()});//Cursor游标和ResultSet很像
45.if(cursor.moveToFirst())//Move the cursor to the first row.This met
hod will return false if the cursor is empty.
46.{
47.int personid=cursor.getInt(cursor.getColumnIndex("personid"));
49.String phone=cursor.getString(cursor.getColumnIndex("phone"));
50.
51.return new Person(personid,name,phone);
52.}
53.return null;
54.}
55./**
56.*删除某一条记录
57.*@param id
58.*/
59.public void delete(Integer id)
60.{
61.SQLiteDatabase db=helper.getWritableDatabase();
62.db.execSQL("delete from person where personid=?",
63.new Object[]{id});
64.}
65.
66./**
67.*得到记录数
68.*@return
69.*/
70.public long getCount()
71.{
72.SQLiteDatabase db=helper.getReadableDatabase();
73.Cursor cursor=db.rawQuery("select count(*)from person",null);
74.cursor.moveToFirst();
75.return cursor.getLong(0);
76.}
77./**
78.*分页查询方法SQL语句跟MySQL的语法一样
79.*@return
80.*/
81.public List
82.{
83.List
84.SQLiteDatabase db=helper.getReadableDatabase();
85.Cursor cursor=db.rawQuery("select*from person limit?,?",
86.new String[]{String.valueOf(offset),Stri
ng.valueOf(maxResult)});
87.while(cursor.moveToNext())
88.{
89.int personid=cursor.getInt(cursor.getColumnIndex("personid"));
90.String name=cursor.getString(cursor.getColumnIndex("name"));
92.
93.persons.add(new Person(personid,name,phone));
94.}
95.
96.return persons;
97.}
98.}
view plaincopy to clipboardprint?
1.package com.zyq.voo;
2.public class Person
3.{
4.private Integer id;
5.private String name;
6.private String phone;
7.
8.public Person(int personid,String name,String phone)
9.{
10.this.id=personid;
https://www.wendangku.net/doc/927321740.html,=name;
12.this.phone=phone;
13.}
14.
15.public Person(String name,String phone)
16.{
https://www.wendangku.net/doc/927321740.html,=name;
18.this.phone=phone;
19.}
20.public String toString()
21.{
22.return"Person[id="+id+",name="+name+",phone="+phone+
"]";
23.}
24.public Integer getId()
25.{
26.return id;
27.}
28.public void setId(Integer id)
29.{
30.this.id=id;
31.}
32.public String getName()
33.{
34.return name;
35.}
36.public void setName(String name)
37.{
https://www.wendangku.net/doc/927321740.html,=name;
39.}
40.public String getPhone()
41.{
42.return phone;
43.}
44.public void setPhone(String phone)
45.{
46.this.phone=phone;
47.}
48.
49.
50.
51.}
https://www.wendangku.net/doc/927321740.html,/linchunhua/article/details/7184439 sqlite数据库只用一个文件就ok,小巧方便,所以是一个非常不错的嵌入式数据库,SQLite 大量的被用于手机,PDA,MP3播放器以及机顶盒设备。 Mozilla Firefox使用SQLite作为数据库。 Mac计算机中的包含了多份SQLite的拷贝,用于不同的应用。 PHP将SQLite作为内置的数据库。 Skype客户端软件在内部使用SQLite。 SymbianOS(智能手机操作平台的领航)内置SQLite。 AOL邮件客户端绑定了SQLite。 Solaris 10在启动过程中需要使用SQLite。 McAfee杀毒软件使用SQLite。 iPhones使用SQLite。 Symbian和Apple以外的很多手机生产厂商使用SQLite。 下面就sqlite中的常用命令和语法介绍 https://www.wendangku.net/doc/927321740.html,/download.html可下载不同操作系统的相关版本sqlite gedit 也可以使用火狐中的插件sqlite manager 新建数据库 sqlite3 databasefilename 检查databasefilename是否存在,如果不存在就创建并进入数据库(如果直接退出,数据库文件不会创建)如果已经存在直接进入数据库对数据库进行操作 sqlite中命令: 以.开头,大小写敏感(数据库对象名称是大小写不敏感的) .exit .help 查看帮助针对命令 .database 显示数据库信息;包含当前数据库的位置 .tables 或者.table 显示表名称没有表则不显示 .schema 命令可以查看创建数据对象时的SQL命令; .schema databaseobjectname查看创建该数据库对象时的SQL的命令;如果没有这个数据库对象就不显示内容,不会有错误提示 .read FILENAME 执行指定文件中的SQL语句 .headers on/off 显示表头默认off .mode list|column|insert|line|tabs|tcl|csv 改变输出格式,具体如下 sqlite> .mode list sqlite> select * from emp; 7369|SMITH|CLERK|7902|17-12-1980|800||20 7499|ALLEN|SALESMAN|7698|20-02-1981|1600|300|30 如果字段值为NULL 默认不显示也就是显示空字符串
SQLite version 3.7.9 2011-11-01 00:52:41 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> create table students( ...> id integer primary key, ...> name text not null unique, ...> sex int default 1, ...> bak text); sqlite> .tables students sqlite> .help .backup ?DB? FILE Backup DB (default "main") to FILE .bail ON|OFF Stop after hitting an error. Default OFF .databases List names and files of attached databases .dump ?TABLE? ... Dump the database in an SQL text format If TABLE specified, only dump tables matching LIKE pattern TABLE. .echo ON|OFF Turn command echo on or off .exit Exit this program .explain ?ON|OFF? Turn output mode suitable for EXPLAIN on or off. With no args, it turns EXPLAIN on. .header(s) ON|OFF Turn display of headers on or off .help Show this message .import FILE TABLE Import data from FILE into TABLE .indices ?TABLE? Show names of all indices If TABLE specified, only show indices for tables matching LIKE pattern TABLE. .load FILE ?ENTRY? Load an extension library .log FILE|off Turn logging on or off. FILE can be stderr/stdout .mode MODE ?TABLE? Set output mode where MODE is one of: csv Comma-separated values column Left-aligned columns. (See .width) html HTML