pull/330/head v_3.0.2
AriaLyy 8 years ago
parent e70456402b
commit 09ca816223
  1. 4
      Aria/build.gradle
  2. 24
      Aria/src/main/java/com/arialyy/aria/orm/DBConfig.java
  3. 11
      Aria/src/main/java/com/arialyy/aria/orm/DbEntity.java
  4. 356
      Aria/src/main/java/com/arialyy/aria/orm/DbUtil.java
  5. 438
      Aria/src/main/java/com/arialyy/aria/orm/SqlHelper.java
  6. 3
      README.md
  7. 1
      app/build.gradle

@ -7,8 +7,8 @@ android {
defaultConfig { defaultConfig {
minSdkVersion 9 minSdkVersion 9
targetSdkVersion 23 targetSdkVersion 23
versionCode 100 versionCode 101
versionName "3.0.0" versionName "3.0.2"
} }
buildTypes { buildTypes {
release { release {

@ -15,18 +15,32 @@
*/ */
package com.arialyy.aria.orm; package com.arialyy.aria.orm;
import android.text.TextUtils;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.upload.UploadEntity;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* Created by Aria.Lao on 2017/4/6. * Created by Aria.Lao on 2017/4/6.
* DB映射表 * 数据库配置信息
*/ */
public class DBMapping { public class DBConfig {
static Map<String, String> mapping = new HashMap<>(); static Map<String, Class> mapping = new HashMap<>();
static String DB_NAME;
static int VERSION = 2;
static { static {
mapping.put("DownloadEntity", "com.arialyy.aria.core.download.DownloadEntity"); if (TextUtils.isEmpty(DB_NAME)) {
mapping.put("UploadEntity", "com.arialyy.aria.core.upload.UploadEntity"); DB_NAME = "AriaLyyDb";
}
if (VERSION == -1) {
VERSION = 1;
}
}
static {
mapping.put("DownloadEntity", DownloadEntity.class);
mapping.put("UploadEntity", UploadEntity.class);
} }
} }

@ -29,7 +29,6 @@ import java.util.List;
public class DbEntity { public class DbEntity {
private static final Object LOCK = new Object(); private static final Object LOCK = new Object();
protected int rowID = -1; protected int rowID = -1;
private DbUtil mUtil = DbUtil.getInstance();
protected DbEntity() { protected DbEntity() {
@ -84,14 +83,14 @@ public class DbEntity {
* 获取所有行的rowid * 获取所有行的rowid
*/ */
public int[] getRowIds() { public int[] getRowIds() {
return mUtil.getRowId(getClass()); return DbUtil.getInstance().getRowId(getClass());
} }
/** /**
* 获取rowid * 获取rowid
*/ */
public int getRowId(@NonNull Object[] wheres, @NonNull Object[] values) { public int getRowId(@NonNull Object[] wheres, @NonNull Object[] values) {
return mUtil.getRowId(getClass(), wheres, values); return DbUtil.getInstance().getRowId(getClass(), wheres, values);
} }
/** /**
@ -117,7 +116,7 @@ public class DbEntity {
* 修改数据 * 修改数据
*/ */
public void update() { public void update() {
mUtil.modifyData(this); DbUtil.getInstance().modifyData(this);
} }
/** /**
@ -125,7 +124,7 @@ public class DbEntity {
*/ */
public void save() { public void save() {
synchronized (LOCK) { synchronized (LOCK) {
if (mUtil.tableExists(getClass()) && thisIsExist()) { if (DbUtil.getInstance().tableExists(getClass()) && thisIsExist()) {
update(); update();
} else { } else {
insert(); insert();
@ -144,7 +143,7 @@ public class DbEntity {
* 插入数据 * 插入数据
*/ */
public void insert() { public void insert() {
mUtil.insertData(this); DbUtil.getInstance().insertData(this);
updateRowID(); updateRowID();
} }

@ -38,13 +38,6 @@ public class DbUtil {
private static final String TAG = "DbUtil"; private static final String TAG = "DbUtil";
private static final Object LOCK = new Object(); private static final Object LOCK = new Object();
private volatile static DbUtil INSTANCE = null; private volatile static DbUtil INSTANCE = null;
private static final int CREATE_TABLE = 0;
private static final int TABLE_EXISTS = 1;
private static final int INSERT_DATA = 2;
private static final int MODIFY_DATA = 3;
private static final int FIND_DATA = 4;
private static final int FIND_ALL_DATA = 5;
private int DEL_DATA = 6;
private int ROW_ID = 7; private int ROW_ID = 7;
private SQLiteDatabase mDb; private SQLiteDatabase mDb;
private SqlHelper mHelper; private SqlHelper mHelper;
@ -54,12 +47,7 @@ public class DbUtil {
} }
private DbUtil(Context context) { private DbUtil(Context context) {
//mHelper = new SqlHelper(context.getApplicationContext(), new SqlHelper.UpgradeListener() { mHelper = SqlHelper.init(context.getApplicationContext());
// @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//
// }
//});
mHelper = new SqlHelper(context.getApplicationContext());
} }
public static DbUtil init(Context context) { public static DbUtil init(Context context) {
@ -80,48 +68,13 @@ public class DbUtil {
return INSTANCE; return INSTANCE;
} }
/**
* 删除某条数据
*/
@Deprecated private synchronized <T extends DbEntity> void delData(Class<T> clazz,
@NonNull Object[] wheres, @NonNull Object[] values) {
mDb = mHelper.getWritableDatabase();
if (wheres.length <= 0 || values.length <= 0) {
Log.e(TAG, "输入删除条件");
return;
} else if (wheres.length != values.length) {
Log.e(TAG, "key 和 vaule 长度不相等");
return;
}
StringBuilder sb = new StringBuilder();
sb.append("DELETE FROM ").append(CommonUtil.getClassName(clazz)).append(" WHERE ");
int i = 0;
for (Object where : wheres) {
sb.append(where).append("=").append("'").append(values[i]).append("'");
sb.append(i >= wheres.length - 1 ? "" : ",");
i++;
}
print(DEL_DATA, sb.toString());
mDb.execSQL(sb.toString());
close();
}
/** /**
* 删除某条数据 * 删除某条数据
*/ */
synchronized <T extends DbEntity> void delData(Class<T> clazz, String... expression) { synchronized <T extends DbEntity> void delData(Class<T> clazz, String... expression) {
CheckUtil.checkSqlExpression(expression); CheckUtil.checkSqlExpression(expression);
mDb = mHelper.getWritableDatabase(); mDb = mHelper.getWritableDatabase();
String sql = "DELETE FROM " + CommonUtil.getClassName(clazz) + " WHERE " + expression[0] + " "; SqlHelper.delData(mDb, clazz, expression);
sql = sql.replace("?", "%s");
Object[] params = new String[expression.length - 1];
for (int i = 0, len = params.length; i < len; i++) {
params[i] = "'" + expression[i + 1] + "'";
}
sql = String.format(sql, params);
print(DEL_DATA, sql);
mDb.execSQL(sql);
close();
} }
/** /**
@ -129,34 +82,7 @@ public class DbUtil {
*/ */
synchronized void modifyData(DbEntity dbEntity) { synchronized void modifyData(DbEntity dbEntity) {
mDb = mHelper.getWritableDatabase(); mDb = mHelper.getWritableDatabase();
Class<?> clazz = dbEntity.getClass(); SqlHelper.modifyData(mDb, dbEntity);
Field[] fields = CommonUtil.getFields(clazz);
if (fields != null && fields.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append("UPDATE ").append(CommonUtil.getClassName(dbEntity)).append(" SET ");
int i = 0;
for (Field field : fields) {
field.setAccessible(true);
if (ignoreField(field)) {
continue;
}
sb.append(i > 0 ? ", " : "");
try {
Object value = field.get(dbEntity);
sb.append(field.getName())
.append("='")
.append(value == null ? "" : value.toString())
.append("'");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
i++;
}
sb.append(" where rowid=").append(dbEntity.rowID);
print(MODIFY_DATA, sb.toString());
mDb.execSQL(sb.toString());
}
close();
} }
/** /**
@ -166,43 +92,15 @@ public class DbUtil {
if (mDb == null || !mDb.isOpen()) { if (mDb == null || !mDb.isOpen()) {
mDb = mHelper.getReadableDatabase(); mDb = mHelper.getReadableDatabase();
} }
return findAllData(mDb, clazz); return SqlHelper.findAllData(mDb, clazz);
}
/**
* 遍历所有数据
*/
static synchronized <T extends DbEntity> List<T> findAllData(SQLiteDatabase db, Class<T> clazz) {
if (!tableExists(db, clazz)) {
createTable(db, clazz, null);
}
StringBuilder sb = new StringBuilder();
sb.append("SELECT rowid, * FROM ").append(CommonUtil.getClassName(clazz));
print(FIND_ALL_DATA, sb.toString());
Cursor cursor = db.rawQuery(sb.toString(), null);
return cursor.getCount() > 0 ? newInstanceEntity(db, clazz, cursor) : null;
} }
/** /**
* 条件查寻数据 * 条件查寻数据
*/ */
synchronized <T extends DbEntity> List<T> findData(Class<T> clazz, String... expression) { synchronized <T extends DbEntity> List<T> findData(Class<T> clazz, String... expression) {
if (!tableExists(clazz)) {
createTable(clazz);
}
mDb = mHelper.getReadableDatabase(); mDb = mHelper.getReadableDatabase();
CheckUtil.checkSqlExpression(expression); return SqlHelper.findData(mDb, clazz, expression);
String sql =
"SELECT rowid, * FROM " + CommonUtil.getClassName(clazz) + " WHERE " + expression[0] + " ";
sql = sql.replace("?", "%s");
Object[] params = new String[expression.length - 1];
for (int i = 0, len = params.length; i < len; i++) {
params[i] = "'" + expression[i + 1] + "'";
}
sql = String.format(sql, params);
print(FIND_DATA, sql);
Cursor cursor = mDb.rawQuery(sql, null);
return cursor.getCount() > 0 ? newInstanceEntity(mDb, clazz, cursor) : null;
} }
/** /**
@ -210,72 +108,8 @@ public class DbUtil {
*/ */
@Deprecated synchronized <T extends DbEntity> List<T> findData(Class<T> clazz, @Deprecated synchronized <T extends DbEntity> List<T> findData(Class<T> clazz,
@NonNull String[] wheres, @NonNull String[] values) { @NonNull String[] wheres, @NonNull String[] values) {
if (!tableExists(clazz)) {
createTable(clazz);
}
mDb = mHelper.getReadableDatabase(); mDb = mHelper.getReadableDatabase();
if (wheres.length <= 0 || values.length <= 0) { return SqlHelper.findData(mDb, clazz, wheres, values);
Log.e(TAG, "请输入查询条件");
return null;
} else if (wheres.length != values.length) {
Log.e(TAG, "key 和 vaule 长度不相等");
return null;
}
StringBuilder sb = new StringBuilder();
sb.append("SELECT rowid, * FROM ").append(CommonUtil.getClassName(clazz)).append(" where ");
int i = 0;
for (Object where : wheres) {
sb.append(where).append("=").append("'").append(values[i]).append("'");
sb.append(i >= wheres.length - 1 ? "" : " AND ");
i++;
}
print(FIND_DATA, sb.toString());
Cursor cursor = mDb.rawQuery(sb.toString(), null);
return cursor.getCount() > 0 ? newInstanceEntity(mDb, clazz, cursor) : null;
}
/**
* 插入数据
*/
static synchronized void insertData(SQLiteDatabase db, DbEntity dbEntity) {
Class<?> clazz = dbEntity.getClass();
if (!tableExists(db, clazz)) {
createTable(db, clazz, null);
}
Field[] fields = CommonUtil.getFields(clazz);
if (fields != null && fields.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ").append(CommonUtil.getClassName(dbEntity)).append("(");
int i = 0;
for (Field field : fields) {
field.setAccessible(true);
if (ignoreField(field)) {
continue;
}
sb.append(i > 0 ? ", " : "");
sb.append(field.getName());
i++;
}
sb.append(") VALUES (");
i = 0;
for (Field field : fields) {
field.setAccessible(true);
if (ignoreField(field)) {
continue;
}
sb.append(i > 0 ? ", " : "");
sb.append("'");
try {
sb.append(field.get(dbEntity)).append("'");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
i++;
}
sb.append(")");
print(INSERT_DATA, sb.toString());
db.execSQL(sb.toString());
}
} }
/** /**
@ -285,8 +119,7 @@ public class DbUtil {
if (mDb == null || !mDb.isOpen()) { if (mDb == null || !mDb.isOpen()) {
mDb = mHelper.getReadableDatabase(); mDb = mHelper.getReadableDatabase();
} }
insertData(mDb, dbEntity); SqlHelper.insertData(mDb, dbEntity);
close();
} }
/** /**
@ -296,85 +129,14 @@ public class DbUtil {
if (mDb == null || !mDb.isOpen()) { if (mDb == null || !mDb.isOpen()) {
mDb = mHelper.getReadableDatabase(); mDb = mHelper.getReadableDatabase();
} }
return tableExists(mDb, clazz); return SqlHelper.tableExists(mDb, clazz);
}
static synchronized boolean tableExists(SQLiteDatabase db, Class clazz) {
Cursor cursor = null;
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name='");
sb.append(CommonUtil.getClassName(clazz));
sb.append("'");
print(TABLE_EXISTS, sb.toString());
cursor = db.rawQuery(sb.toString(), null);
if (cursor != null && cursor.moveToNext()) {
int count = cursor.getInt(0);
if (count > 0) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) cursor.close();
if (db != null) {
db.close();
}
}
return false;
}
static synchronized void createTable(SQLiteDatabase db, Class clazz, String tableName) {
Field[] fields = CommonUtil.getFields(clazz);
if (fields != null && fields.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append("create table ")
.append(TextUtils.isEmpty(tableName) ? CommonUtil.getClassName(clazz) : tableName)
.append("(");
for (Field field : fields) {
field.setAccessible(true);
if (ignoreField(field)) {
continue;
}
sb.append(field.getName());
Class<?> type = field.getType();
if (type == String.class) {
sb.append(" varchar");
} else if (type == int.class || type == Integer.class) {
sb.append(" interger");
} else if (type == float.class || type == Float.class) {
sb.append(" float");
} else if (type == double.class || type == Double.class) {
sb.append(" double");
} else if (type == long.class || type == Long.class) {
sb.append(" bigint");
} else if (type == boolean.class || type == Boolean.class) {
sb.append(" boolean");
} else if (type == java.util.Date.class || type == java.sql.Date.class) {
sb.append(" data");
} else if (type == byte.class || type == Byte.class) {
sb.append(" blob");
} else {
continue;
}
sb.append(",");
}
String str = sb.toString();
str = str.substring(0, str.length() - 1) + ");";
print(CREATE_TABLE, str);
db.execSQL(str);
}
if (db != null) {
db.close();
}
} }
synchronized void createTable(Class clazz, String tableName) { synchronized void createTable(Class clazz, String tableName) {
if (mDb == null || !mDb.isOpen()) { if (mDb == null || !mDb.isOpen()) {
mDb = mHelper.getWritableDatabase(); mDb = mHelper.getWritableDatabase();
} }
createTable(mDb, clazz, tableName); SqlHelper.createTable(mDb, clazz, tableName);
} }
/** /**
@ -384,48 +146,6 @@ public class DbUtil {
createTable(clazz, null); createTable(clazz, null);
} }
/**
* @return true 忽略该字段
*/
static boolean ignoreField(Field field) {
// field.isSynthetic(), 使用as热启动App时,AS会自动给你的clss添加change字段
Ignore ignore = field.getAnnotation(Ignore.class);
return (ignore != null && ignore.value()) || field.isSynthetic();
}
/**
* 打印数据库日志
*
* @param type {@link DbUtil}
*/
private static void print(int type, String sql) {
if (true) {
return;
}
String str = "";
switch (type) {
case CREATE_TABLE:
str = "创建表 >>>> ";
break;
case TABLE_EXISTS:
str = "表是否存在 >>>> ";
break;
case INSERT_DATA:
str = "插入数据 >>>> ";
break;
case MODIFY_DATA:
str = "修改数据 >>>> ";
break;
case FIND_DATA:
str = "查询一行数据 >>>> ";
break;
case FIND_ALL_DATA:
str = "遍历整个数据库 >>>> ";
break;
}
Log.v(TAG, str + sql);
}
/** /**
* 关闭数据库 * 关闭数据库
*/ */
@ -472,67 +192,11 @@ public class DbUtil {
sb.append(i >= wheres.length - 1 ? "" : ","); sb.append(i >= wheres.length - 1 ? "" : ",");
i++; i++;
} }
print(ROW_ID, sb.toString()); SqlHelper.print(ROW_ID, sb.toString());
Cursor c = mDb.rawQuery(sb.toString(), null); Cursor c = mDb.rawQuery(sb.toString(), null);
int id = c.getColumnIndex("rowid"); int id = c.getColumnIndex("rowid");
c.close(); c.close();
close(); close();
return id; return id;
} }
/**
* 根据数据游标创建一个具体的对象
*/
private static synchronized <T extends DbEntity> List<T> newInstanceEntity(SQLiteDatabase db,
Class<T> clazz, Cursor cursor) {
Field[] fields = CommonUtil.getFields(clazz);
List<T> entitys = new ArrayList<>();
if (fields != null && fields.length > 0) {
try {
while (cursor.moveToNext()) {
T entity = clazz.newInstance();
for (Field field : fields) {
field.setAccessible(true);
if (ignoreField(field)) {
continue;
}
Class<?> type = field.getType();
int column = cursor.getColumnIndex(field.getName());
if (type == String.class) {
field.set(entity, cursor.getString(column));
} else if (type == int.class || type == Integer.class) {
field.setInt(entity, cursor.getInt(column));
} else if (type == float.class || type == Float.class) {
field.setFloat(entity, cursor.getFloat(column));
} else if (type == double.class || type == Double.class) {
field.setDouble(entity, cursor.getDouble(column));
} else if (type == long.class || type == Long.class) {
field.setLong(entity, cursor.getLong(column));
} else if (type == boolean.class || type == Boolean.class) {
field.setBoolean(entity, !cursor.getString(column).equalsIgnoreCase("false"));
} else if (type == java.util.Date.class || type == java.sql.Date.class) {
field.set(entity, new Date(cursor.getString(column)));
} else if (type == byte[].class) {
field.set(entity, cursor.getBlob(column));
} else {
continue;
}
}
entity.rowID = cursor.getInt(cursor.getColumnIndex("rowid"));
entitys.add(entity);
//Log.d(TAG, "rowid ==> " + entity.rowID);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
cursor.close();
//close();
if (db != null) {
db.close();
}
return entitys;
}
} }

@ -20,11 +20,15 @@ import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import com.arialyy.aria.util.CheckUtil;
import com.arialyy.aria.util.CommonUtil; import com.arialyy.aria.util.CommonUtil;
import java.io.File;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -33,30 +37,30 @@ import java.util.Set;
* sql帮助类 * sql帮助类
*/ */
final class SqlHelper extends SQLiteOpenHelper { final class SqlHelper extends SQLiteOpenHelper {
interface UpgradeListener { private static final String TAG = "SqlHelper";
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion); private static final int CREATE_TABLE = 0;
} private static final int TABLE_EXISTS = 1;
private static final int INSERT_DATA = 2;
private static final int MODIFY_DATA = 3;
private static final int FIND_DATA = 4;
private static final int FIND_ALL_DATA = 5;
private static final int DEL_DATA = 6;
private UpgradeListener mUpgradeListener; private static volatile SqlHelper INSTANCE = null;
static String DB_NAME; private static final Object LOCK = new Object();
static int VERSION = -1;
static { static SqlHelper init(Context context) {
if (TextUtils.isEmpty(DB_NAME)) { if (INSTANCE == null) {
DB_NAME = "AriaLyyDb"; synchronized (LOCK) {
INSTANCE = new SqlHelper(context.getApplicationContext());
checkTable(INSTANCE.getWritableDatabase());
} }
if (VERSION == -1) {
VERSION = 1;
} }
return INSTANCE;
} }
//SqlHelper(Context context, UpgradeListener listener) { private SqlHelper(Context context) {
// super(context, DB_NAME, null, VERSION); super(context, DBConfig.DB_NAME, null, DBConfig.VERSION);
// mUpgradeListener = listener;
//}
SqlHelper(Context context) {
super(context, DB_NAME, null, VERSION);
} }
@Override public void onCreate(SQLiteDatabase db) { @Override public void onCreate(SQLiteDatabase db) {
@ -64,12 +68,15 @@ final class SqlHelper extends SQLiteOpenHelper {
} }
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
if (oldVersion < newVersion) { if (oldVersion < newVersion) {
handleDbUpdate(db); handleDbUpdate(db);
} }
} catch (ClassNotFoundException e) { }
e.printStackTrace();
@Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//super.onDowngrade(db, oldVersion, newVersion);
if (oldVersion > newVersion) {
handleDbUpdate(db);
} }
} }
@ -78,7 +85,7 @@ final class SqlHelper extends SQLiteOpenHelper {
* *
* @throws ClassNotFoundException * @throws ClassNotFoundException
*/ */
private void handleDbUpdate(SQLiteDatabase db) throws ClassNotFoundException { private void handleDbUpdate(SQLiteDatabase db) {
if (db == null) { if (db == null) {
Log.d("SqlHelper", "db 为 null"); Log.d("SqlHelper", "db 为 null");
return; return;
@ -86,10 +93,11 @@ final class SqlHelper extends SQLiteOpenHelper {
Log.d("SqlHelper", "db已关闭"); Log.d("SqlHelper", "db已关闭");
return; return;
} }
Set<String> tables = DBMapping.mapping.keySet(); Set<String> tables = DBConfig.mapping.keySet();
for (String tableName : tables) { for (String tableName : tables) {
Class clazz = Class.forName(DBMapping.mapping.get(tableName)); Class clazz = DBConfig.mapping.get(tableName);
if (DbUtil.tableExists(db, clazz)) { if (tableExists(db, clazz)) {
//db = checkDb(db);
String countColumnSql = "SELECT rowid FROM " + tableName; String countColumnSql = "SELECT rowid FROM " + tableName;
Cursor cursor = db.rawQuery(countColumnSql, null); Cursor cursor = db.rawQuery(countColumnSql, null);
int dbColumnNum = cursor.getColumnCount(); int dbColumnNum = cursor.getColumnCount();
@ -105,24 +113,27 @@ final class SqlHelper extends SQLiteOpenHelper {
* 备份 * 备份
*/ */
private void back(SQLiteDatabase db, Class clazz) { private void back(SQLiteDatabase db, Class clazz) {
db = checkDb(db);
String oldTableName = CommonUtil.getClassName(clazz); String oldTableName = CommonUtil.getClassName(clazz);
//备份数据 //备份数据
List<DbEntity> list = DbUtil.findAllData(db, clazz); List<DbEntity> list = findAllData(db, clazz);
//修改原来表名字 //修改原来表名字
String alertSql = "alter table " + oldTableName + " rename to " + oldTableName + "_temp"; String alertSql = "alter table " + oldTableName + " rename to " + oldTableName + "_temp";
db.beginTransaction(); db.beginTransaction();
db.execSQL(alertSql); db.execSQL(alertSql);
//创建一个原来新表 //创建一个原来新表
DbUtil.createTable(db, clazz, null); createTable(db, clazz, null);
if (list != null && list.size() > 0) {
for (DbEntity entity : list) { for (DbEntity entity : list) {
DbUtil.insertData(db, entity); insertData(db, entity);
}
} }
//删除原来的表 //删除原来的表
String deleteSQL = "drop table IF EXISTS " + oldTableName + "_temp"; String deleteSQL = "drop table IF EXISTS " + oldTableName + "_temp";
db.execSQL(deleteSQL); db.execSQL(deleteSQL);
db.setTransactionSuccessful(); db.setTransactionSuccessful();
db.endTransaction(); db.endTransaction();
db.close(); close(db);
} }
/** /**
@ -134,7 +145,7 @@ final class SqlHelper extends SQLiteOpenHelper {
if (fields != null && fields.length > 0) { if (fields != null && fields.length > 0) {
for (Field field : fields) { for (Field field : fields) {
field.setAccessible(true); field.setAccessible(true);
if (DbUtil.ignoreField(field)) { if (ignoreField(field)) {
continue; continue;
} }
count++; count++;
@ -142,4 +153,369 @@ final class SqlHelper extends SQLiteOpenHelper {
} }
return count; return count;
} }
/**
* 检查数据库表如果配置的表不存在则创建新表
*/
static synchronized void checkTable(SQLiteDatabase db) {
db = checkDb(db);
Set<String> tables = DBConfig.mapping.keySet();
for (String tableName : tables) {
Class clazz = null;
clazz = DBConfig.mapping.get(tableName);
if (!tableExists(db, clazz)) {
createTable(db, clazz, null);
}
}
}
/**
* 条件查寻数据
*/
static synchronized <T extends DbEntity> List<T> findData(SQLiteDatabase db, Class<T> clazz,
String... expression) {
db = checkDb(db);
CheckUtil.checkSqlExpression(expression);
String sql =
"SELECT rowid, * FROM " + CommonUtil.getClassName(clazz) + " WHERE " + expression[0] + " ";
sql = sql.replace("?", "%s");
Object[] params = new String[expression.length - 1];
for (int i = 0, len = params.length; i < len; i++) {
params[i] = "'" + expression[i + 1] + "'";
}
sql = String.format(sql, params);
print(FIND_DATA, sql);
Cursor cursor = db.rawQuery(sql, null);
List<T> data = cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null;
close(db);
return data;
}
/**
* 条件查寻数据
*/
@Deprecated static synchronized <T extends DbEntity> List<T> findData(SQLiteDatabase db,
Class<T> clazz, @NonNull String[] wheres, @NonNull String[] values) {
db = checkDb(db);
if (wheres.length <= 0 || values.length <= 0) {
Log.e(TAG, "请输入查询条件");
return null;
} else if (wheres.length != values.length) {
Log.e(TAG, "key 和 vaule 长度不相等");
return null;
}
StringBuilder sb = new StringBuilder();
sb.append("SELECT rowid, * FROM ").append(CommonUtil.getClassName(clazz)).append(" where ");
int i = 0;
for (Object where : wheres) {
sb.append(where).append("=").append("'").append(values[i]).append("'");
sb.append(i >= wheres.length - 1 ? "" : " AND ");
i++;
}
print(FIND_DATA, sb.toString());
Cursor cursor = db.rawQuery(sb.toString(), null);
List<T> data = cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null;
close(db);
return data;
}
/**
* 遍历所有数据
*/
static synchronized <T extends DbEntity> List<T> findAllData(SQLiteDatabase db, Class<T> clazz) {
db = checkDb(db);
StringBuilder sb = new StringBuilder();
sb.append("SELECT rowid, * FROM ").append(CommonUtil.getClassName(clazz));
print(FIND_ALL_DATA, sb.toString());
Cursor cursor = db.rawQuery(sb.toString(), null);
List<T> data = cursor.getCount() > 0 ? newInstanceEntity(clazz, cursor) : null;
close(db);
return data;
}
/**
* 删除某条数据
*/
static synchronized <T extends DbEntity> void delData(SQLiteDatabase db, Class<T> clazz,
String... expression) {
db = checkDb(db);
CheckUtil.checkSqlExpression(expression);
String sql = "DELETE FROM " + CommonUtil.getClassName(clazz) + " WHERE " + expression[0] + " ";
sql = sql.replace("?", "%s");
Object[] params = new String[expression.length - 1];
for (int i = 0, len = params.length; i < len; i++) {
params[i] = "'" + expression[i + 1] + "'";
}
sql = String.format(sql, params);
SqlHelper.print(DEL_DATA, sql);
db.execSQL(sql);
close(db);
}
/**
* 修改某行数据
*/
static synchronized void modifyData(SQLiteDatabase db, DbEntity dbEntity) {
db = checkDb(db);
Class<?> clazz = dbEntity.getClass();
Field[] fields = CommonUtil.getFields(clazz);
if (fields != null && fields.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append("UPDATE ").append(CommonUtil.getClassName(dbEntity)).append(" SET ");
int i = 0;
for (Field field : fields) {
field.setAccessible(true);
if (SqlHelper.ignoreField(field)) {
continue;
}
sb.append(i > 0 ? ", " : "");
try {
Object value = field.get(dbEntity);
sb.append(field.getName())
.append("='")
.append(value == null ? "" : value.toString())
.append("'");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
i++;
}
sb.append(" where rowid=").append(dbEntity.rowID);
print(MODIFY_DATA, sb.toString());
db.execSQL(sb.toString());
}
close(db);
}
/**
* 插入数据
*/
static synchronized void insertData(SQLiteDatabase db, DbEntity dbEntity) {
db = checkDb(db);
Class<?> clazz = dbEntity.getClass();
Field[] fields = CommonUtil.getFields(clazz);
if (fields != null && fields.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ").append(CommonUtil.getClassName(dbEntity)).append("(");
int i = 0;
for (Field field : fields) {
field.setAccessible(true);
if (ignoreField(field)) {
continue;
}
sb.append(i > 0 ? ", " : "");
sb.append(field.getName());
i++;
}
sb.append(") VALUES (");
i = 0;
for (Field field : fields) {
field.setAccessible(true);
if (ignoreField(field)) {
continue;
}
sb.append(i > 0 ? ", " : "");
sb.append("'");
try {
sb.append(field.get(dbEntity)).append("'");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
i++;
}
sb.append(")");
print(INSERT_DATA, sb.toString());
db.execSQL(sb.toString());
}
close(db);
}
/**
* 查找表是否存在
*
* @param clazz 数据库实体
* @return true该数据库实体对应的表存在false不存在
*/
static synchronized boolean tableExists(SQLiteDatabase db, Class clazz) {
db = checkDb(db);
Cursor cursor = null;
try {
StringBuilder sb = new StringBuilder();
sb.append("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name='");
sb.append(CommonUtil.getClassName(clazz));
sb.append("'");
print(TABLE_EXISTS, sb.toString());
cursor = db.rawQuery(sb.toString(), null);
if (cursor != null && cursor.moveToNext()) {
int count = cursor.getInt(0);
if (count > 0) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) cursor.close();
close(db);
}
return false;
}
/**
* 创建表
*
* @param clazz 数据库实体
* @param tableName 数据库实体的类名
*/
static synchronized void createTable(SQLiteDatabase db, Class clazz, String tableName) {
db = checkDb(db);
Field[] fields = CommonUtil.getFields(clazz);
if (fields != null && fields.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append("create table ")
.append(TextUtils.isEmpty(tableName) ? CommonUtil.getClassName(clazz) : tableName)
.append("(");
for (Field field : fields) {
field.setAccessible(true);
if (ignoreField(field)) {
continue;
}
sb.append(field.getName());
Class<?> type = field.getType();
if (type == String.class) {
sb.append(" varchar");
} else if (type == int.class || type == Integer.class) {
sb.append(" interger");
} else if (type == float.class || type == Float.class) {
sb.append(" float");
} else if (type == double.class || type == Double.class) {
sb.append(" double");
} else if (type == long.class || type == Long.class) {
sb.append(" bigint");
} else if (type == boolean.class || type == Boolean.class) {
sb.append(" boolean");
} else if (type == java.util.Date.class || type == java.sql.Date.class) {
sb.append(" data");
} else if (type == byte.class || type == Byte.class) {
sb.append(" blob");
} else {
continue;
}
sb.append(",");
}
String str = sb.toString();
str = str.substring(0, str.length() - 1) + ");";
print(CREATE_TABLE, str);
db.execSQL(str);
}
close(db);
}
/**
* 打印数据库日志
*
* @param type {@link DbUtil}
*/
static void print(int type, String sql) {
if (true) {
return;
}
String str = "";
switch (type) {
case CREATE_TABLE:
str = "创建表 >>>> ";
break;
case TABLE_EXISTS:
str = "表是否存在 >>>> ";
break;
case INSERT_DATA:
str = "插入数据 >>>> ";
break;
case MODIFY_DATA:
str = "修改数据 >>>> ";
break;
case FIND_DATA:
str = "查询一行数据 >>>> ";
break;
case FIND_ALL_DATA:
str = "遍历整个数据库 >>>> ";
break;
}
Log.v(TAG, str + sql);
}
/**
* 根据数据游标创建一个具体的对象
*/
static synchronized <T extends DbEntity> List<T> newInstanceEntity(Class<T> clazz,
Cursor cursor) {
Field[] fields = CommonUtil.getFields(clazz);
List<T> entitys = new ArrayList<>();
if (fields != null && fields.length > 0) {
try {
while (cursor.moveToNext()) {
T entity = clazz.newInstance();
for (Field field : fields) {
field.setAccessible(true);
if (ignoreField(field)) {
continue;
}
Class<?> type = field.getType();
int column = cursor.getColumnIndex(field.getName());
if (column == -1) continue;
if (type == String.class) {
field.set(entity, cursor.getString(column));
} else if (type == int.class || type == Integer.class) {
field.setInt(entity, cursor.getInt(column));
} else if (type == float.class || type == Float.class) {
field.setFloat(entity, cursor.getFloat(column));
} else if (type == double.class || type == Double.class) {
field.setDouble(entity, cursor.getDouble(column));
} else if (type == long.class || type == Long.class) {
field.setLong(entity, cursor.getLong(column));
} else if (type == boolean.class || type == Boolean.class) {
field.setBoolean(entity, !cursor.getString(column).equalsIgnoreCase("false"));
} else if (type == java.util.Date.class || type == java.sql.Date.class) {
field.set(entity, new Date(cursor.getString(column)));
} else if (type == byte[].class) {
field.set(entity, cursor.getBlob(column));
} else {
continue;
}
}
entity.rowID = cursor.getInt(cursor.getColumnIndex("rowid"));
entitys.add(entity);
//Log.d(TAG, "rowid ==> " + entity.rowID);
}
cursor.close();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return entitys;
}
private static void close(SQLiteDatabase db) {
//if (db != null && db.isOpen()) db.close();
}
private static SQLiteDatabase checkDb(SQLiteDatabase db) {
if (db == null || !db.isOpen()) {
db = INSTANCE.getWritableDatabase();
}
return db;
}
/**
* @return true 忽略该字段
*/
static boolean ignoreField(Field field) {
// field.isSynthetic(), 使用as热启动App时,AS会自动给你的clss添加change字段
Ignore ignore = field.getAnnotation(Ignore.class);
return (ignore != null && ignore.value()) || field.isSynthetic() || Modifier.isStatic(
field.getModifiers()) || Modifier.isFinal(field.getModifiers());
}
} }

@ -20,7 +20,7 @@ Aria怎样使用?
## 下载 ## 下载
[![Download](https://api.bintray.com/packages/arialyy/maven/Aria/images/download.svg)](https://bintray.com/arialyy/maven/Aria/_latestVersion)</br> [![Download](https://api.bintray.com/packages/arialyy/maven/Aria/images/download.svg)](https://bintray.com/arialyy/maven/Aria/_latestVersion)</br>
```java ```java
compile 'com.arialyy.aria:Aria:3.0.0' compile 'com.arialyy.aria:Aria:3.0.2'
``` ```
## 示例 ## 示例
@ -143,6 +143,7 @@ compile 'com.arialyy.aria:Aria:3.0.0'
*** ***
## 开发日志 ## 开发日志
+ v_3.0.2 支持30x重定向链接下载
+ v_3.0.0 添加上传任务支持,修复一些已发现的bug + v_3.0.0 添加上传任务支持,修复一些已发现的bug
+ v_2.4.4 修复不支持断点的下载链接拿不到文件大小的问题 + v_2.4.4 修复不支持断点的下载链接拿不到文件大小的问题
+ v_2.4.3 修复404链接卡顿的问题 + v_2.4.3 修复404链接卡顿的问题

@ -38,4 +38,5 @@ dependencies {
compile 'com.arialyy.frame:MVVM2:2.2.0' compile 'com.arialyy.frame:MVVM2:2.2.0'
compile 'com.arialyy.absadapter:AbsAdapter:1.1.2' compile 'com.arialyy.absadapter:AbsAdapter:1.1.2'
compile project(':Aria') compile project(':Aria')
// compile 'com.arialyy.aria:Aria:3.0.0'
} }

Loading…
Cancel
Save