安卓使用【Ormlite框架】
一:首先下载 ORMLite Jar 包
先去 ORMLite官网下载jar包 写博客时,目前最新的,对于Android为:ormlite-android-5.0.jar 和 ormlite-core-5.0.jar ;
文章图片
二:配置Bean类
package hyi.bean;三:编写Helper类
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName= "Book")
public class BeanDou{
@DatabaseField(generatedId= true)
private int id;
@DatabaseField(columnName= "name")
public String name;
@DatabaseField(columnName= "price")
public String price;
//记得使用该框架时,要具有无参数构造方法
public BeanDou() {
}
public BeanDou(int id, String name, String price) {
this.id = id;
this.name = name;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
@Override
public String toString() {
return "BeanDou{" +
"id=" + id +
", name='" + name + '\'' +
", price='" + price + '\'' +
'}';
}
}
package hyi.dao;四:编写DAO类
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
【安卓使用【Ormlite框架】】import hyi.bean.BeanDou;
import java.util.HashMap;
import java.util.Map;
public class AndroidDatabaseHelper extends OrmLiteSqliteOpenHelper {
//数据库名字
public static final String DB_NAME="BookStore.db";
//数据库版本
public static final int DB_VERSION=1;
public AndroidDatabaseHelper(Context context){
super(context,DB_NAME,null,DB_VERSION);
//创建
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, BeanDou.class);
}catch (Exception e ){}
}
//更新
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
System.out.println("oldVersion=" + oldVersion + "newVersion=" + newVersion);
try{
switch (oldVersion){
case 1:
//在数据库版本1的下一版本,Book表中新添加了 book_type 字段
getDao(BeanDou.class).executeRaw("alter table book add column book_type varchar(20)");
case 2:
// TableUtils.createTable(connectionSource, MyBean2.class);
//在数据库版本2的下一版本,新增加了一张表
default:
break;
//显然这样处理比较暴力
//TableUtils.dropTable(connectionSource, MyBean.class, true);
//onCreate(sqLiteDatabase, connectionSource);
}}
catch (Exception e){}
}
}
private staticAndroidDatabaseHelper instance;
//单例获取该helper
publicstatic AndroidDatabaseHelper getHelper(Context context) {
if (instance == null) {
synchronized (AndroidDatabaseHelper.class) {
if (instance == null) {
instance = new AndroidDatabaseHelper(context);
}
}
return instance;
}
}
private Map daos=new HashMap<>();
publicsynchronized Dao getDao(Class clazz){
Dao dao=null;
String className=clazz.getSimpleName();
//containskey(。。)方法判断是否包含该键名
if (daos.containsKey(className)){
dao=daos.get(clazz);
}
if (dao==null){
dao=super.getDao(clazz);
daos.put(className,dao);
}
returndao;
}
public void close(){
super.close();
for (String key :daos.keySet()){
Dao dao=daos.get(key);
dao=null;
}
}
}
1:接口编写:
public interface MyDataImpl {
//插入
void insert(ArrayList beanArrayList);
void insert(MyBean myBean);
void update(String name, String price);
void update2(String columnName, String columnValue);
void update3(String queryColumnName, String queryColumnValue, String setColumnName, String setColumnValue);
void delete(String name);
int deleteAll();
ArrayList queryPrice(String name);
String queryAuthor(String name, String price);
long queryCount();
ArrayList queryId(int id);
ArrayList queryAll();
}
public class MyDataDaoimplementsMyDataImpl{五:测试
private MyDatabaseHelper mHelper;
private Dao dao;
private Context mContext;
private static MyDataDao instance;
protected MyDataDao(Context context) {
this.mContext = context;
try {
mHelper = MyDatabaseHelper.getHelper(mContext);
dao = mHelper.getDao(MyBean.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static MyDataDao getInstance(Context context) {
if (instance == null) {
synchronized (MyDataDao.class) {
if (instance == null) {
instance = new MyDataDao(context);
}
}
}
return instance;
}
@Overridepublic void insert(MyBean myBean) {
try {
//事务操作/* TransactionManager.callInTransaction(mHelper.getConnectionSource(), new Callable() {
@Override
public Void call() throws Exception {
return null;
}
}); */dao.create(myBean);
//dao.createOrUpdate(myBean); //和上一行的方法效果一样} catch (SQLException e) {
e.printStackTrace();
}
}
@Overridepublic void insert(ArrayList beanArrayList) {
try {
dao.create(beanArrayList);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Overridepublic void update(String name, String price) {
ArrayList list = null;
try {
list = (ArrayList) dao.queryForEq("name", name);
if (list != null) {
for (MyBean bean : list) {
bean.setPrice(price);
dao.update(bean);
//dao.createOrUpdate(bean); //和上一行的方法效果一样}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Overridepublic void update2(String columnName, String columnValue) {
try {
//下面这两个代码的意思一样dao.updateBuilder().updateColumnValue(columnName, columnValue).update();
//dao.updateRaw("update Book set " + columnName + "=?", new String[]{columnValue}); } catch (SQLException e) {
e.printStackTrace();
}
}
@Overridepublic void update3(String queryColumnName, String queryColumnValue, String setColumnName, String setColumnValue) {
try {
String sql = "update Book set " + setColumnName + "= '" + setColumnValue + "' where " + queryColumnName + "= '" + queryColumnValue + "'";
System.out.println("MyDataDao.update3 sql=" + sql);
dao.updateRaw(sql);
//dao.updateRaw("update Book set price= '33333元' where name= '西游记'"); //等价于上面的写法} catch (SQLException e) {
e.printStackTrace();
}
}
@Overridepublic void delete(String name) {
ArrayList list = null;
try {
list = (ArrayList) dao.queryForEq("name", name);
if (list != null) {
for (MyBean bean : list) {
dao.delete(bean);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/*** @return-1:删除数据异常0:无数据*/@Overridepublic int deleteAll() {
int number = -1;
try {
number = dao.deleteBuilder().delete(); //返回删除的数据条数例如:删除1条数据,返回1,依次类推。//dao.deleteBuilder().where().eq("name", "记").reset(); //????} catch (SQLException e) {
e.printStackTrace();
}
return number;
}
@Overridepublic ArrayList queryPrice(String name) {
List list = null;
ArrayList strings = null;
try {
list = dao.queryForEq("name", name);
if (list != null) {
strings = new ArrayList<>();
for (MyBean myBean : list) {
strings.add(myBean.getPrice());
}
/*for (int i = 0; i < list.size(); i++) {
strings.add(list.get(i).getPrice());
}*/}
} catch (SQLException e) {
e.printStackTrace();
}
return strings;
}
@Overridepublic String queryAuthor(String name1, String price1) {
List list = null;
String author = "";
try {
list = dao.queryBuilder().where().eq("name", name1).and().eq("price", price1).query(); //上述相当与:select * from Book where name = name1 and price = price1 ; if (list != null) {
for (MyBean myBean : list) {
author = myBean.getAuthor();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return author; //说明:如果这个 author 是唯一的,可以这样的返回。如果是多个的话,要返回一个ArrayList 类型}
/*** @return表中数据的个数*/@Overridepublic long queryCount() {
long number = 0;
try {
number = dao.queryBuilder().countOf();
} catch (SQLException e) {
e.printStackTrace();
}
return number;
}
/*** @paramid 这个id 就是表中,每次插入数据,自己递增的id 字段*/@Overridepublic ArrayList queryId(int id) {
ArrayList list = null;
try {
MyBean myBean = dao.queryForId(id);
if (myBean != null) {
list = new ArrayList<>();
list.add(myBean);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
@Overridepublic ArrayList queryAll() {
ArrayList list = null;
try {
list = (ArrayList) dao.queryForAll();
if (list != null) {
return list;
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public boolean delteTables(Context context, String DBname) {
//?????return false;
}
/**
* 这个方法可以的
*/public boolean delteDatabases(Context context, String DBname) {
return context.deleteDatabase(DBname);
}
}
推荐阅读
- 宽容谁
- 我要做大厨
- 增长黑客的海盗法则
- 画画吗()
- 2019-02-13——今天谈梦想()
- 远去的风筝
- 三十年后的广场舞大爷
- 叙述作文
- 20190302|20190302 复盘翻盘
- 学无止境,人生还很长