使用 sqlitedatabase 操作 sqlite 数据库
android提供了一个名为sqlitedatabase的类,该类封装了一些操作数据库的api,使用该类可以完成对数据进行添加(create)、查询(retrieve)、更新(update)和删除(delete)操作(这些操作简称为crud)。对sqlitedatabase的学习,我们应该重点掌握execsql()和rawquery()方法。 execsql()方法可以执行insert、delete、update和create table之类有更改行为的sql语句; rawquery()方法用于执行select语句。
execsql()方法的使用例子:
sqlitedatabase db = ….;
db.execsql(“insert into person(name, age) values(‘测试数据’, 4)”);
db.close();
执行上面sql语句会往person表中添加进一条记录,在实际应用中, 语句中的“测试数据”这些参数值会由用户输入界面提供,如果把用户输入的内容原样组拼到上面的insert语句, 当用户输入的内容含有单引号时,组拼出来的sql语句就会存在语法错误。要解决这个问题需要对单引号进行转义,也就是把单引号转换成两个单引号。有些时候用户往往还会输入像“ & ”这些特殊sql符号,为保证组拼好的sql语句语法正确,必须对sql语句中的这些特殊sql符号都进行转义,显然,对每条sql语句都做这样的处理工作是比较烦琐的。 sqlitedatabase类提供了一个重载后的execsql(string sql, object[] bindargs)方法,使用这个方法可以解决前面提到的问题,因为这个方法支持使用占位符参数(?)。使用例子如下:
sqlitedatabase db = ….;
db.execsql(“insert into person(name, age) values(?,?)”, new object[]{“测试数据”, 4});
db.close();
execsql(string sql, object[] bindargs)方法的第一个参数为sql语句,第二个参数为sql语句中占位符参数的值,参数值在数组中的顺序要和占位符的位置对应。
*/
//类没有实例化,是不能用作父类构造器的参数,必须声明为静态
private static final string name = “itcast”; //数据库名称
private static final int version = 1; //数据库版本
public databasehelper(context context) {
//第三个参数cursorfactory指定在执行查询时获得一个游标实例的工厂类,设置为null,代表使用系统默认的工厂类
super(context, name, null, version);
}
@override public void oncreate(sqlitedatabase db) {
db.execsql(“create table if not exists person (personid integer primary key autoincrement, name varchar(20), age integer)”);
}
@override public void onupgrade(sqlitedatabase db, int oldversion, int newversion) {
db.execsql(” alter table person add phone varchar(12) null “); //往表中增加一列
// drop table if exists person 删除表
}
}
//在实际项目开发中,当数据库表结构发生更新时,应该避免用户存放于数//据库中的数据丢失。
android提供了一个名为sqlitedatabase的类,该类封装了一些操作数据库的api,使用该类可以完成对数据进行添加(create)、查询(retrieve)、更新(update)和删除(delete)操作(这些操作简称为crud)。对sqlitedatabase的学习,我们应该重点掌握execsql()和rawquery()方法。 execsql()方法可以执行insert、delete、update和create table之类有更改行为的sql语句; rawquery()方法用于执行select语句。
execsql()方法的使用例子:
sqlitedatabase db = ….;
db.execsql(“insert into person(name, age) values(‘测试数据’, 4)”);
db.close();
执行上面sql语句会往person表中添加进一条记录,在实际应用中, 语句中的“测试数据”这些参数值会由用户输入界面提供,如果把用户输入的内容原样组拼到上面的insert语句, 当用户输入的内容含有单引号时,组拼出来的sql语句就会存在语法错误。要解决这个问题需要对单引号进行转义,也就是把单引号转换成两个单引号。有些时候用户往往还会输入像“ & ”这些特殊sql符号,为保证组拼好的sql语句语法正确,必须对sql语句中的这些特殊sql符号都进行转义,显然,对每条sql语句都做这样的处理工作是比较烦琐的。 sqlitedatabase类提供了一个重载后的execsql(string sql, object[] bindargs)方法,使用这个方法可以解决前面提到的问题,因为这个方法支持使用占位符参数(?)。使用例子如下:
sqlitedatabase db = ….;
db.execsql(“insert into person(name, age) values(?,?)”, new object[]{“测试数据”, 4});
db.close();
execsql(string sql, object[] bindargs)方法的第一个参数为sql语句,第二个参数为sql语句中占位符参数的值,参数值在数组中的顺序要和占位符的位置对应。
*/
sqlitedatabase的rawquery() 用于执行select语句,使用例子如下: sqlitedatabase db = ….;
cursor cursor = db.rawquery(“select * from person”, null);
while (cursor.movetonext()) {
int personid = cursor.getint(0); //获取第一列的值,第一列的索引从0开始
string name = cursor.getstring(1);//获取第二列的值
int age = cursor.getint(2);//获取第三列的值
}
cursor.close();
db.close();
rawquery()方法的第一个参数为select语句;第二个参数为select语句中占位符参数的值,如果select语句没有使用占位符,该参数可以设置为null。带占位符参数的select语句使用例子如下:
cursor cursor = db.rawquery(“select * from person where name like ? and age=?”, new string[]{“%传智%”, “4”});
cursor是结果集游标,用于对结果集进行随机访问,如果大家熟悉jdbc, 其实cursor与jdbc中的resultset作用很相似。使用movetonext()方法可以将游标从当前行移动到下一行,如果已经移过了结果集的最后一行,返回结果为false,否则为true。另外cursor 还有常用的movetoprevious()方法(用于将游标从当前行移动到上一行,如果已经移过了结果集的第一行,返回值为false,否则为true )、movetofirst()方法(用于将游标移动到结果集的第一行,如果结果集为空,返回值为false,否则为true )和movetolast()方法(用于将游标移动到结果集的最后一行,如果结果集为空,返回值为false,否则为true ) 。
*/
除了前面给大家介绍的execsql()和rawquery()方法, sqlitedatabase还专门提供了对应于添加、删除、更新、查询的操作方法: insert()、delete()、update()和query() 。这些方法实际上是给那些不太了解sql语法的菜鸟使用的,对于熟悉sql语法的程序员而言,直接使用execsql()和rawquery()方法执行sql语句就能完成数据的添加、删除、更新、查询操作。
insert()方法用于添加数据,各个字段的数据使用contentvalues进行存放。 contentvalues类似于map,相对于map,它提供了存取数据对应的put(string key, xxx value)和getasxxx(string key)方法, key为字段名称,value为字段值,xxx指的是各种常用的数据类型,如:string、integer等。
sqlitedatabase db = databasehelper.getwritabledatabase();
contentvalues values = new contentvalues();
values.put(“name”, “测试数据”);
values.put(“age”, 4);
long rowid = db.insert(“person”, null, values);//返回新添记录的行号,与主键id无关
不管第三个参数是否包含数据,执行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。
*/
delete()方法的使用:
sqlitedatabase db = databasehelper.getwritabledatabase();
db.delete(“person”, “personid<?”, new string[]{“2”});
db.close();
上面代码用于从person表中删除personid小于2的记录。
update()方法的使用:
sqlitedatabase db = databasehelper.getwritabledatabase();
contentvalues values = new contentvalues();
values.put(“name”, “测试数据”);//key为字段名,value为值
db.update(“person”, values, “personid=?”, new string[]{“1”});
db.close();
上面代码用于把person表中personid等于1的记录的name字段的值改为“测试数据”。
*/
query()方法实际上是把select语句拆分成了若干个组成部分,然后作为方法的输入参数:
sqlitedatabase db = databasehelper.getwritabledatabase();
cursor cursor = db.query(“person”, new string[]{“personid,name,age”}, “name like ?”, new string[]{“%传智%”}, null, null, “personid desc”, “1,2”);
while (cursor.movetonext()) {
int personid = cursor.getint(0); //获取第一列的值,第一列的索引从0开始
string name = cursor.getstring(1);//获取第二列的值
int age = cursor.getint(2);//获取第三列的值
}
cursor.close();
db.close();
上面代码用于从person表中查找name字段含有“传智”的记录,匹配的记录按personid降序排序,对排序后的结果略过第一条记录,只获取2条记录。
query(table, columns, selection, selectionargs, groupby, having, orderby, limit)方法各参数的含义:
table:表名。相当于select语句from关键字后面的部分。如果是多表联合查询,可以用逗号将两个表名分开。
columns:要查询出来的列名。相当于select语句select关键字后面的部分。
selection:查询条件子句,相当于select语句where关键字后面的部分,在条件子句允许使用占位符“?”
selectionargs:对应于selection语句中占位符的值,值在数组中的位置与占位符在语句中的位置必须一致,否则就会有异常。
groupby:相当于select语句group by关键字后面的部分
having:相当于select语句having关键字后面的部分
orderby:相当于select语句order by关键字后面的部分,如:personid desc, age asc;
limit:指定偏移量和获取的记录数,相当于select语句limit关键字后面的部分。
*/
import android.app.activity;
import android.os.bundle;
public class mainactivity extends activity
{
@override
public void oncreate(bundle savedinstancestate)
{
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
}
}
import java.util.list;
import android.test.androidtestcase;
import android.util.log;
import com.zyq.service.dbopenhelper;
import com.zyq.service.personservice;
import com.zyq.voo.person;
/**
* 测试方法 通过junit 单元测试
* 1.>实例化测试类
* 2.>把与应用有关的上下文信息传入到测试类实例
* 3.>运行测试方法
* @author administrator
*
*/
public class personservicetest extends androidtestcase
{
private final static string tag=”personservicetest”;
/**
* 测试创建数据库
* @throws throwable
*/
public void testcreatedb() throws throwable
{
dbopenhelper dbopenhelper=new dbopenhelper(this.getcontext());
dbopenhelper.getreadabledatabase(); //create and/or open a database.
}
/**
* 测试新增一条记录
* @throws throwable
*/
public void testsave() throws throwable
{
personservice personservice=new personservice(this.getcontext());
personservice.save(new person(“zhangsan”,”1360215320″));
personservice.save(new person(“lisi”,”1123″));
personservice.save(new person(“lili”,”232″));
personservice.save(new person(“wangda”,”123123″));
personservice.save(new person(“laozhu”,”234532″));
}
/**
* 查找一条记录
* @throws throwable
*/
public void testfind() throws throwable
{
personservice personservice=new personservice(this.getcontext());
person person=personservice.find(1);
log.i(tag,person.tostring());
}
/**
* 测试更新一条记录
* @throws throwable
*/
public void testupdate() throws throwable
{
personservice personservice=new personservice(this.getcontext());
person person=personservice.find(1);
person.setname(“lisi”);
personservice.update(person);
}
/**
* 测试得到所有记录数
* @throws throwable
*/
public void testgetcount() throws throwable
{
personservice personservice=new personservice(this.getcontext());
log.i(tag, personservice.getcount()+”********”);
}
/**
* 测试分页
* @throws throwable
*/
public void testscroll() throws throwable
{
personservice personservice=new personservice(this.getcontext());
list<person> persons=personservice.getscrolldata(3, 3);
for(person person:persons)
{
log.i(tag, person.tostring());
}
}
/**
* 测试删除一条记录
* @throws throwable
*/
public void testdelete() throws throwable
{
personservice personservice=new personservice(this.getcontext());
personservice.delete(5);
}
}
import android.content.context;
import android.database.sqlite.sqlitedatabase;
import android.database.sqlite.sqliteopenhelper;
public class dbopenhelper extends sqliteopenhelper
{
/**
* 如果想额外的增加一个字段(需求)
* 可以把版本号更改掉 但必须 >=1
* 更改版本号之后 会根据版本号判断是不是上次创建的时候 (目前的版本号和传入的版本号是否一致 )
* 如果不是会执行 onupgrade() 方法
* @param context
*/
public dbopenhelper(context context)
{
super(context, “zyq.db”, null, 2);
}
/**
* 在数据库创建的时候第一个调用的方法
* 适合创建表结构
*/
@override
public void oncreate(sqlitedatabase db)
{
db.execsql(“create table person (personid integer primary key autoincrement, name varchar(20))”);//创建表
}
/**
* 更新表结构 在数据库版本号发生改变的时候调用
* 应用升级
*/
@override
public void onupgrade(sqlitedatabase db, int oldversion, int newversion)
{
db.execsql(“alter table person add phone varchar(12) null “); //往表中增加一列
}
}
<manifest xmlns:android=”https://schemas.android.com/apk/res/android”
package=”com.zyq.db”
android:versioncode=”1″
android:versionname=”1.0″>
<application android:icon=”@drawable/icon” android:label=”@string/app_name”>
<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>
<uses-sdk android:minsdkversion=”8″ />
<instrumentation android:name=”android.test.instrumentationtestrunner”
android:targetpackage=”com.zyq.db” android:label=”tests for my app” />
</manifest>
import java.util.arraylist;
import java.util.list;
import android.content.context;
import android.database.cursor;
import android.database.sqlite.sqlitedatabase;
import com.zyq.voo.person;
public class personservice
{
private dbopenhelper helper;
public personservice(context context)
{
helper=new dbopenhelper(context);
}
/**
* 新增一条记录
* @param person
*/
public void save(person person)
{
sqlitedatabase db=helper.getwritabledatabase();//create and/or open a database that will be used for reading and writing
db.execsql(“insert into person(name,phone) values(?,?)”,new object[]{person.getname().trim(),person.getphone().trim()});//使用占位符进行转译
// db.close(); 不关数据库连接 。可以提高性能 因为创建数据库的时候的操作模式是私有的。
//代表此数据库,只能被本应用所访问 单用户的,可以维持长久的链接
}
/**
* 更新某一条记录
* @param person
*/
public void update(person person)
{
sqlitedatabase db=helper.getwritabledatabase();
db.execsql(“update person set phone=?,name=? where personid=?”,
new object[]{person.getphone().trim(),person.getname().trim(),person.getid()});
}
/**
* 根据id查询某条记录
* @param id
* @return
*/
public person find(integer id)
{
sqlitedatabase db=helper.getreadabledatabase();
cursor cursor=db.rawquery(“select * from person where personid=?”, new string[]{id.tostring()});//cursor 游标和 resultset 很像
if(cursor.movetofirst())//move the cursor to the first row. this method will return false if the cursor is empty.
{
int personid=cursor.getint(cursor.getcolumnindex(“personid”));
string name=cursor.getstring(cursor.getcolumnindex(“name”));
string phone=cursor.getstring(cursor.getcolumnindex(“phone”));
return new person(personid,name,phone);
}
return null;
}
/**
* 删除某一条记录
* @param id
*/
public void delete(integer id)
{
sqlitedatabase db=helper.getwritabledatabase();
db.execsql(“delete from person where personid=?”,
new object[]{id});
}
/**
* 得到记录数
* @return
*/
public long getcount()
{
sqlitedatabase db=helper.getreadabledatabase();
cursor cursor=db.rawquery(“select count(*) from person”, null);
cursor.movetofirst();
return cursor.getlong(0);
}
/**
* 分页查询方法 sql语句跟mysql的语法一样
* @return
*/
public list<person> getscrolldata(int offset,int maxresult)
{
list<person> persons=new arraylist<person>();
sqlitedatabase db=helper.getreadabledatabase();
cursor cursor=db.rawquery(“select * from person limit ?,?”,
new string[]{string.valueof(offset),string.valueof(maxresult)});
while (cursor.movetonext())
{
int personid=cursor.getint(cursor.getcolumnindex(“personid”));
string name=cursor.getstring(cursor.getcolumnindex(“name”));
string phone=cursor.getstring(cursor.getcolumnindex(“phone”));
persons.add(new person(personid,name,phone));
}
return persons;
}
}
public class person
{
private integer id;
private string name;
private string phone;
public person(int personid, string name, string phone)
{
this.id=personid;
this.name=name;
this.phone=phone;
}
public person(string name, string phone)
{
this.name = name;
this.phone = phone;
}
public string tostring()
{
return “person [id=” + id + “, name=” + name + “, phone=” + phone + “]”;
}
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 string getphone()
{
return phone;
}
public void setphone(string phone)
{
this.phone = phone;
}
}
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/addevelopment/939532.html