zoukankan      html  css  js  c++  java
  • Android数据存储---SQLite

    SQLite是一款轻量级数据库,支持大部分SQL语句。

    下面我们来看看如何使用:

    1.写一个工具类继承SQLiteOpenHelper,建数据库,建person表

    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    public class DBOpenHelper extends SQLiteOpenHelper {            // 定义工具类, 继承SQLiteOpenHelper
    	
    	public DBOpenHelper(Context context) {			// 创建对象的时候, 需要传入上下文环境
    		super(context, "itcast.db", null, 4);
    		/*
    		 * 由于父类没有无参构造函数, 必须显式调用有参的构造函数
    		 * 参数1: 上下文环境, 用来确定数据库文件存储的目录
    		 * 参数2: 数据库文件的名字
    		 * 参数3: 生成游标的工厂, 填null就是使用默认的
    		 * 参数4: 数据库的版本, 从1开始,只能从低版本更新到高版本
    		 */
    	}
    
    	@Override
    	public void onCreate(SQLiteDatabase db) {
    		System.out.println("onCreate");
    		db.execSQL("CREATE TABLE person(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20))");		// 执行SQL语句, 创建表
    	}
    
    	//数据库版本更新时调用此方法
    	@Override
    	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    		System.out.println("onUpgrade");
    		db.execSQL("ALTER TABLE person ADD balance INTEGER");
    	}
    
    }
    

    2.对Person对象进行增删改查

    import java.util.ArrayList;
    import java.util.List;
    
    import cn.itcast.sqlite.domain.Person;
    
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    
    public class PersonDao {
    	private DBOpenHelper helper;
    	
    	public PersonDao(Context context) {
    		helper = new DBOpenHelper(context);
    	}
    
    	public void insert(Person p) {
    		SQLiteDatabase db = helper.getWritableDatabase();	        // 获取数据库连接(可写的)
    		ContentValues values = new ContentValues();			// 类似于Map的容器, 键是String, 用来存放列名, 值是Object, 用来存要插入的数据
    		values.put("name", p.getName());				// 某些情况下, 程序会接收一个ContentValues参数, 这时用这种方式存储比较方便
    		values.put("balance", p.getBalance());
    		/*
    		 * 参数1:表名
    		 * 参数2:用于指定空值字段的名称
    		 * 参数3:插入的参数,null 表示用来在想插入一条除了主键全部为空的记录时使用
    		 * 返回:插入记录的id
    		 */
    		long id = db.insert("person", null, values);				
    		System.out.println("插入的记录的id是: " + id);
    		db.close();
    	}
    	
    	public void delete(int id) {
    		SQLiteDatabase db = helper.getWritableDatabase();
    		int rows = db.delete("person", "id=?", new String[] { id + "" });
    		System.out.println("删除了" + rows + "行");
    		db.close();
    	}
    
    	public void update(Person p) {
    		SQLiteDatabase db = helper.getWritableDatabase();
    		ContentValues values = new ContentValues();
    		values.put("name", p.getName());
    		values.put("balance", p.getBalance());
    		int rows = db.update("person", values, "id=?", new String[] { p.getId() + "" });
    		System.out.println("更新了" + rows + "行");
    		db.close();
    	}
    	
    	//query one
    	public Person query(int id) {
    		SQLiteDatabase db = helper.getReadableDatabase();			// 获取数据库连接(可读的)
    		Cursor c = db.query("person", new String[] { "name", "balance" }, "id=?", new String[] { id + "" }, null, null, null);
    		Person p = null;
    		if (c.moveToNext()) {															// 判断游标是否包含下一条记录, 如果包含将游标向后移动一位
    			String name = c.getString(c.getColumnIndex("name"));		// 获取"name"字段的索引, 然后根据索引获取数据
    			int balance = c.getInt(1);												// 获取1号索引上的数据
    			p = new Person(id, name, balance);	
    		}
    		c.close();
    		db.close();
    		return p;
    	}
    	//查询所有
    	public List<Person> queryAll() {
    		SQLiteDatabase db = helper.getReadableDatabase();					
    		Cursor c = db.query("person", null, null, null, null, null, null);
    		List<Person> persons = new ArrayList<Person>();
    		while (c.moveToNext()) {										
    			Person p = new Person(c.getInt(0), c.getString(1), c.getInt(2));
    			persons.add(p);
    		}
    		c.close();
    		db.close();
    		return persons;
    	}
    	//此方法是在ListView设置SimpleCursorAdapter适配器时调用
    	public Cursor queryAllCursor() {
    		SQLiteDatabase db = helper.getReadableDatabase();				
    		 /*
             * 使用Cursor相关的Adapter时需要一个自增的列,且名字必需为 _id
             */
    		Cursor c = db.query("person", new String[] { "id _id", "name", "balance" }, null, null, null, null, null);
    		return c;
    	}
    	//查询有多少记录
    	public int queryCount() {
    		SQLiteDatabase db = helper.getReadableDatabase();					
    		Cursor c = db.query("person", new String[]{ "COUNT(*)" }, null, null, null, null, null);	
    		c.moveToNext();
    		int count = c.getInt(0);
    		c.close();
    		db.close();
    		return count;
    	}
    	//分页
    	public List<Person> queryPage(int pageNum, int capacity) {		
    		String offset = (pageNum - 1) * capacity + "";		// 偏移量
    		String len = capacity + "";									// 个数
    		SQLiteDatabase db = helper.getReadableDatabase();					
    		Cursor c = db.query("person", null, null, null, null, null, null, offset + "," + len);	
    		List<Person> persons = new ArrayList<Person>();
    		while (c.moveToNext()) {										
    			Person p = new Person(c.getInt(0), c.getString(1), c.getInt(2));
    			persons.add(p);
    		}
    		c.close();
    		db.close();
    		return persons;
    	}
    	//使用事物提交
    	public void remit(int from, int to, int amount) {
    		SQLiteDatabase db = helper.getWritableDatabase();
    		try {
    			db.beginTransaction();			// 开始事务
    			db.execSQL("UPDATE person SET balance=balance-? WHERE id=?", new Object[] { amount, from });
    			db.execSQL("UPDATE person SET balance=balance+? WHERE id=?", new Object[] { amount, to });
    			db.setTransactionSuccessful();	// 设置成功点, 在事务结束时, 成功点之前的操作会被提交
    		} finally {
    			db.endTransaction();			// 结束事务, 将成功点之前的操作提交
    			db.close();
    		}
    	}
    	
    }

    3.写一个Test类,测试方法

    import java.util.List;
    
    import cn.itcast.sqlite.domain.Person;
    
    import android.database.Cursor;
    import android.test.AndroidTestCase;
    
    public class DBTest extends AndroidTestCase {
    
    	public void testCreateDatabase() {
    		DBOpenHelper helper = new DBOpenHelper(getContext());
    		helper.getWritableDatabase();	
    		/*
    		 * 获取可写的数据连接
    		 * 数据库文件不存在时, 会创建数据库文件, 并且执行onCreate()方法
    		 * 数据库文件存在, 并且版本没有改变时, 不执行任何方法
    		 * 数据库文件存在, 版本提升, 执行onUpgrade()方法
    		 */
    	}
    	
    	public void testInsert() {
    		PersonDao dao = new PersonDao(getContext());
    		dao.insert(new Person("xxx", 9999));
    	}
    	
    	public void testDelete() {
    		PersonDao dao = new PersonDao(getContext());
    		dao.delete(106);
    	}
    	
    	public void testUpdate() {
    		PersonDao dao = new PersonDao(getContext());
    		dao.update(new Person(2, "李四", 10000));
    		dao.update(new Person(3, "王五", 10000));
    	}
    	
    	public void testQuery() {
    		PersonDao dao = new PersonDao(getContext());
    		System.out.println(dao.query(5));
    	}
    	
    	public void testQueryAll() {
    		PersonDao dao = new PersonDao(getContext());
    		List<Person> persons = dao.queryAll();
    		for (Person p : persons)
    			System.out.println(p);
    	}
    	
    	public void testQueryCount() {
    		PersonDao dao = new PersonDao(getContext());
    		System.out.println(dao.queryCount());
    	}
    	
    	public void testQueryPage() {
    		PersonDao dao = new PersonDao(getContext());
    		List<Person> persons = dao.queryPage(2, 10);
    		for (Person p : persons)
    			System.out.println(p);
    	}
    	
    	public void testRemit() {
    		PersonDao dao = new PersonDao(getContext());
    		dao.remit(3, 2, 1000);
    	}
    	public void testQueryAllCursor(){
    		PersonDao dao = new PersonDao(getContext());
    		Cursor c=dao.queryAllCursor();
    		while(c.moveToNext()){
    			System.out.println(c.getString(c.getColumnIndex("name")));
    		}
    	}
    	
    }



  • 相关阅读:
    制作本地 odoo deb包安装镜像
    用Lua实现string的trim()方法
    UGUI之控件以及按钮的监听事件系统
    UGUI之不规则按钮的响应区域
    Unity接第三方SDK时遇到的坑
    AI设计
    Unity UGUI 的RectTransform参数的设置
    Lua string库详解
    lua正则表达式如何匹配中文
    kubernetes pod的生命周期
  • 原文地址:https://www.cnblogs.com/fzll/p/3954620.html
Copyright © 2011-2022 走看看