004】【SQLite数据库】

项目源码下载SQLite数据库轻量级关系型数据库

创建数据库需要使用的api:SQLiteOpenHelper

必须定义一个构造方法:

//arg1:数据库文件的名字//arg2:游标工厂//arg3:数据库版本public MyOpenHelper(Context context, String name, CursorFactory factory, int version){}数据库被创建时会调用:onCreate方法数据库升级时会调用:onUpgrade方法创建数据库 //创建OpenHelper对象MyOpenHelper oh = new MyOpenHelper(getContext(), “person.db”, null, 1);//获得数据库对象,如果数据库不存在,先创建数据库,后获得,如果存在,则直接获得SQLiteDatabase db = oh.getWritableDatabase();public void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stubdb.execSQL(“autoincrement,name char(10), phone char(20), money integer(20))”);}数据库的增删改查SQL语句* insert into person (name, phone, money) values (‘张三’, ‘159874611’, 2000);* _id = 4;* update person set money = 6000 where name = ‘李四’;* select name, phone from person where name = ‘张三’;执行SQL语句实现增删改查//插入db.execSQL(“insert into person (name, phone, money) values (?, ?, ?);”, new Object[]{“张三”, 15987461, 75000});//查找Cursor cs = db.rawQuery(“select _id, name, money from person where name = ?;”, new String[]{“张三”});测试方法执行前会调用此方法() throws Exception {super.setUp();//获取虚拟上下文对象oh = new MyOpenHelper(getContext(), “people.db”, null, 1);}使用api实现增删改查插入//以键值对的形式保存要存入数据库的数据ContentValues cv = new ContentValues();cv.put(“name”, “刘能”);cv.put(“phone”, 1651646);cv.put(“money”, 3500);//返回值是改行的主键,如果出错返回-1long i = db.insert(“person”, null, cv);删除//返回值是删除的行数int i = db.delete(“person”, “_id = ? and name = ?”, new String[]{“1”, “张三”});修改ContentValues cv = new ContentValues();cv.put(“money”, 25000);int i = db.update(“person”, cv, “name = ?”, new String[]{“赵四”});查询Cursor cs = db.query([]{“张三”}, null, null, null);while(cs.moveToNext()){//获取指定列的索引值String name = cs.getString(cs.getColumnIndex(“name”));String money = cs.getString(cs.getColumnIndex(“money”));System.out.println(name + “;” + money);}事务try {//开启事务db.beginTransaction();db.setTransactionSuccessful();} finally{//关闭事务//如果此时已经设置事务执行成功,则sql语句生效,,否则不生效db.endTransaction();}把数据库的数据显示至屏幕任意插入一些数据 定义业务bean:Person.java读取数据库的所有数据Cursor cs = db.query(“person”, null, null, null, null, null, null);while(cs.moveToNext()){String name = cs.getString(cs.getColumnIndex(“name”));String phone = cs.getString(cs.getColumnIndex(“phone”));String money = cs.getString(cs.getColumnIndex(“money”));//把读到的数据封装至Person对象Person p = new Person(name, phone, money);//把person对象保存至集合中people.add(p);}把集合中的数据显示至屏幕LinearLayout ll = (LinearLayout) findViewById(R.id.ll);for(Person p : people){//创建TextView,每条数据用一个文本框显示TextView tv = new TextView(this);tv.setText(p.toString());//把文本框设置为ll的子节点ll.addView(tv);}分页查询Cursor cs = db.query(“person”, null, null, null, null, null, null, “0, 10”);

志在山顶的人,不会贪念山腰的风景。

004】【SQLite数据库】

相关文章:

你感兴趣的文章:

标签云: