Android基础之十五数据存储 之 SQLite数据库的封装

本文主要探讨了Android中SQLite数据库的封装技术,包括如何创建、操作数据库以及优化数据存储过程,旨在提供一种高效的数据管理解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SQLite数据库的封装



一:建立实体类对象,字段名一定要和数据库里的一一对应
Book.java
<span style="font-size:14px;">package com.example.entity;

public class Book {
	private Integer  id;
	private String  author;
	private double price;
	private Integer pages;
	private String name;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public Integer getPages() {
		return pages;
	}
	public void setPages(Integer pages) {
		this.pages = pages;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Book() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Book(Integer id, String author, double price, Integer pages,
			String name) {
		super();
		this.id = id;
		this.author = author;
		this.price = price;
		this.pages = pages;
		this.name = name;
	}
	@Override
	public String toString() {
		return "Book [id=" + id + ", author=" + author + ", price=" + price
				+ ", pages=" + pages + ", name=" + name + "]";
	}	
	
}</span>
Category.java
package com.example.entity;

public class Category {
	private Integer  id;
	private String category_name;
	private Integer category_code;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getCategory_name() {
		return category_name;
	}
	public void setCategory_name(String category_name) {
		this.category_name = category_name;
	}
	public Integer getCategory_code() {
		return category_code;
	}
	public void setCategory_code(Integer category_code) {
		this.category_code = category_code;
	}
	public Category() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Category(Integer id, String category_name, Integer category_code) {
		super();
		this.id = id;
		this.category_name = category_name;
		this.category_code = category_code;
	}
	
}
二:在dao层建立数据库管理类
package com.example.sqllitehelp.dao;

import java.util.ArrayList;
import java.util.List;

import com.example.entity.Book;
import com.example.sqllitehelp.MainActivity;
import com.example.sqllitehelp.MyDatabaseHelper;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Toast;


public class sqlitedao   {
	private MyDatabaseHelper myDatabaseHlper;
	public sqlitedao(Context context) {
		myDatabaseHlper=new MyDatabaseHelper(context, "BookStore.db", null, 1);
	}
	public void add_data(Book  bk ){
		SQLiteDatabase  db=myDatabaseHlper.getWritableDatabase();
		ContentValues values=new ContentValues();
		//开始组装第一条数据
		values.put("name", bk.getName());
		values.put("author", bk.getAuthor());
		values.put("pages",bk.getPages());
		values.put("price", bk.getPrice());
		db.insert("Book", "name", values);
		//当values参数为空或者里面没有内容的时候,
		//我们insert是会失败的(底层数据库不允许插入一个空行),为了防止这种情况,我们要在这里指定一个列名,
		//到时候如果发现将要插入的行为空行时,就会将你指定的这个列名的值设为null,然后再向数据库中插入。
	}
	//修改数据
	public void Upata_data(Book bk){
		SQLiteDatabase  db=myDatabaseHlper.getWritableDatabase();
		ContentValues values=new ContentValues();
		values.put("price",bk.getPrice() );
		db.update("Book", values, "name =?", new String []{bk.getName()+""});

	}
	//查询数据
	public  List query_data(){
		//查询Book表中的数据
		List<Book> list=new ArrayList<Book>();
		SQLiteDatabase  db=myDatabaseHlper.getWritableDatabase();
		ContentValues values=new ContentValues();
		Cursor cursor=db.query("Book", null, null, null, null, null, null);	
		if(cursor.moveToFirst()){
			//遍历cursor对象,取出数据并打印。
			do{
				Integer id=cursor.getInt(cursor.getColumnIndex("id"));
				String name=cursor.getString(cursor.getColumnIndex("name"));
				String author=cursor.getString(cursor.getColumnIndex("author"));
				double pages=cursor.getDouble(cursor.getColumnIndex("pages"));
				Integer price=cursor.getInt(cursor.getColumnIndex("price"));
				//System.out.println("名字"+name+"作者"+author+"书页"+pages+"价格"+price);
				list.add(new Book(id, author, pages, price, name));
			}while(cursor.moveToNext());				
		}
		return list;

	}
	//删除数据
	public void delete_data(Book bk){
		SQLiteDatabase  db=myDatabaseHlper.getWritableDatabase();
		ContentValues values=new ContentValues();
		db.delete("Book", "pages >?", new String []{bk.getPages()+""});
	}
}
怎么测试呢?????在AndroidManifest.xml中加入
<instrumentation 
   android:name="android.test.InstrumentationTestRunner"
   android:targetPackage="com.example.sqllitehelp"
   ></instrumentation>

 <uses-library android:name="android.test.runner"/>


具体请看:
地方
<span style="color:#333333;"><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sqllitehelp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="17" />
	</span><span style="color:#ff0000;"><instrumentation 
	    android:name="android.test.InstrumentationTestRunner"
	    android:targetPackage="com.example.sqllitehelp"
	    ></instrumentation></span><span style="color:#333333;">
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.sqllitehelp.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>
        </span><span style="color:#ff0000;"><uses-library android:name="android.test.runner"/></span><span style="color:#333333;">
    </application>

</manifest></span>
三测试操作数据库是否成功
<span style="font-size:14px;">package com.sqlitehelp.text;

import java.util.ArrayList;
import java.util.List;

import com.example.entity.Book;
import com.example.sqllitehelp.dao.sqlitedao;

import android.test.AndroidTestCase;

public class SqlistTest  extends AndroidTestCase{
	public void testadd(){
		sqlitedao dao=new sqlitedao(getContext());
		Book  book=new Book(1, "zhu", 12.15, 12, "codeadd");
		dao.add_data(book);
		System.out.println("添加数据成功");
	}
	public void query_add(){
		sqlitedao dao=new sqlitedao(getContext());
		List<Book> list=dao.query_data();
		System.out.println("查询数据成功"+list);
		
	}
}</span>




一个简单的基于AndroidSqlite数据库的操作封装,它有如下的好处:便捷地创建表和增添表字段灵活的数据类型处理通过操作对象来insert或者update表记录支持多种查询方式,支持多表自定义的复杂查询,支持分页查询支持事务快速开始:    1. 设计表:@Table(name="t_user") public class UserModel {     @Table.Column(name="user_id",type=Column.TYPE_INTEGER,isPrimaryKey=true)     public Integer userId;     @Table.Column(name="user_name",type=Column.TYPE_STRING,isNull=false)     public String userName;     @Table.Column(name="born_date",type=Column.TYPE_TIMESTAMP)     public Date bornDate;     @Table.Column(name="pictrue",type=Column.TYPE_BLOB)     public byte[] pictrue;     @Table.Column(name="is_login",type=Column.TYPE_BOOLEAN)     public Boolean isLogin;     @Table.Column(name="weight",type=Column.TYPE_DOUBLE)     public Double weight; }2. 初始化对象:SQLiteDatabase db = context.openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null); DbSqlite dbSqlite = new DbSqlite(db); IBaseDao userDAO = DaoFactory.createGenericDao(dbSqlite, UserModel.class);3. 创建表:userDAO.createTable(); 4. Insert 记录:UserModel user = new UserModel(); user.userName = "darcy"; user.isLogin = true; user.weight = 60.5; user.bornDate = new Date(); byte[] picture = {0x1,0x2,0x3,0x4}; user.pictrue = picture; userDAO.insert(user);5. Update 记录:UserModel user = new UserModel(); user.weight = 88.0; userDAO.update(user, "user_name=?", "darcy");6. 查询://单条结果查询 UserModel user = userDAO.queryFirstRecord("user_name=?", "darcy"); //一般查询 List userList = userDAO.query("user_name=? and weight > ?", "darcy" , "60"); //分页查询 PagingList pagingList = userDAO.pagingQuery(null, null, 1, 3);7. 事务支持:DBTransaction.transact(mDb, new DBTransaction.DBTransactionInterface() {         @Override         public void onTransact() {             // to do                 } };8. 更新表(目前只支持添加字段)@Table(name="t_user" , version=2) //修改表版本 public class UserModel {     //members above...     //new columns     @Table.Column(name="new_column_1",type=Column.TYPE_INTEGER)     public Integer newColumn;     @Table.Column(name="new_column_2",type=Column.TYPE_INTEGER)     public Integer newColumn2; } userDAO.updateTable();缺点和不足:还没支持多对一或者一多的关系没支持联合主键没支持表的外键设计其他...实例:SqliteLookup(Android内查看Sqlite数据库利器): https://github.com/YeDaxia/SqliteLookup 标签:SQLiteUtils
大家好,个人觉得用Sqlite数据库时,经常需要进行机械性的CRUD操作,故对其进行了一下封装,希望能起到抛砖引玉的作用。 目的:封装共有的CRUD 下面简单的说一下使用步骤,如果觉得多余,可以无视。 1. 实现自己的DBHelper: /** * * @author Kee.Li * * 1. 继承了SmartDBHelper,不需要重写SQLiteOpenHelper的那两个方法 * 2. 父类构造方法参数modelClasses是实体类的数组,也就是需要生产表的类的Class数组 * */ public class DBHelper extends SmartDBHelper { //数据库名称 private final static String DATABASE_NAME = "books.db"; //数据库版本 private final static int DATABASE_VERSION = 2; //需要生成数据库表的类的数组 private final static Class<?>[] modelClasses = {Book.class,User.class}; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION,modelClasses); } } 2.创建app需要的实体,也就是对应的数据库表(这里的实体添加到DBHelper的modelClasses数组中) /** * 数据库的实体 * @author Kee.Li * 关于注解: * Table: 此类对应的数据库表名 * Id:标识此属性为数据库自增长的id,应为int型 * Column:标识此属性对应的数据库字段名 */ @Table(name="t_books") public class Book{ @Id @Column(name="book_id") private int bookId; @Column(name="book_name") private String bookName; @Column(name="book_author") private String bookAuthor; //set get 方法省略.... } 3. 实现DAO,也就是对实体的CRUD类 /** * @author Kee.Li * * 此类只需要继承TemplateDAO,在构造方法里面给父类的属性dbHelper赋值,即可实现CRUD操作 * 若有复杂的操作,可以自定义方法 */ public class BookDAO extends TemplateDAO { /** * 创建DAO时初始化连接数据库对象helper * @param context */ public BookDAO(Context context) { super(new DBHelper(context)); } } 4. activity的调用 bookDAO = new BookDAO(this); List books = bookDAO.find(); 好了,到此结束,如果有什么好的建议或者意见,希望可以共同学习!谢谢大家!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值