diff --git a/.idea/compiler.xml b/.idea/compiler.xml
new file mode 100644
index 0000000..61a9130
--- /dev/null
+++ b/.idea/compiler.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/gradle.xml b/.idea/gradle.xml
index 232b563..32bd02b 100644
--- a/.idea/gradle.xml
+++ b/.idea/gradle.xml
@@ -16,6 +16,7 @@
+
diff --git a/.idea/misc.xml b/.idea/misc.xml
index be0cc41..915410e 100644
--- a/.idea/misc.xml
+++ b/.idea/misc.xml
@@ -1,7 +1,7 @@
-
+
diff --git a/app/src/main/java/com/kongzue/dbv3demo/MainActivity.java b/app/src/main/java/com/kongzue/dbv3demo/MainActivity.java
index 58757f3..a21dd13 100644
--- a/app/src/main/java/com/kongzue/dbv3demo/MainActivity.java
+++ b/app/src/main/java/com/kongzue/dbv3demo/MainActivity.java
@@ -32,6 +32,7 @@ public class MainActivity extends AppCompatActivity {
private Button btnAddDemoData;
private Button btnAddJsonData;
private Button btnAddMapData;
+ private Button btnAddOrUpdate;
private EditText editName;
private EditText editAge;
private RadioGroup rgpGender;
@@ -67,6 +68,7 @@ protected void onCreate(Bundle savedInstanceState) {
btnAddDemoData = findViewById(R.id.btn_add_demo_data);
btnAddJsonData = findViewById(R.id.btn_add_json_data);
btnAddMapData = findViewById(R.id.btn_add_map_data);
+ btnAddOrUpdate = findViewById(R.id.btn_add_or_update);
editName = findViewById(R.id.edit_name);
editAge = findViewById(R.id.edit_age);
rgpGender = findViewById(R.id.rgp_gender);
@@ -319,6 +321,20 @@ public void onClick(View v) {
logAllData();
}
});
+
+ btnAddOrUpdate.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ Map map = new HashMap<>();
+ map.put("username", "张三");
+ map.put("age", 99);
+ map.put("gender", 1);
+ map.put("isVIP", false);
+
+ DB.getTable("user").addOrUpdate("username",new DBData(map));
+ logAllData();
+ }
+ });
}
private void addDemoData() {
diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml
index e7a0dc1..bb4ecc8 100644
--- a/app/src/main/res/layout/activity_main.xml
+++ b/app/src/main/res/layout/activity_main.xml
@@ -52,6 +52,12 @@
android:layout_height="wrap_content"
android:text="通过Map添加数据" />
+
+
diff --git a/dbv3/build.gradle b/dbv3/build.gradle
index 9f15946..d9089a5 100644
--- a/dbv3/build.gradle
+++ b/dbv3/build.gradle
@@ -6,7 +6,7 @@ def siteUrl = 'https://github.com/kongzue/DBV3' //项目在github主页地址
def gitUrl = 'https://github.com/kongzue/DBV3.git' //Git仓库的地址
group = "com.kongzue.db"//发布aar前缀根节点
-version = "3.0.3"//发布aar的库版本
+version = "3.0.3.4"//发布aar的库版本
android {
compileSdkVersion 29
@@ -15,7 +15,7 @@ android {
minSdkVersion 19
targetSdkVersion 29
versionCode 15
- versionName "3.0.3"
+ versionName "3.0.3.4"
}
buildTypes {
diff --git a/dbv3/src/main/java/com/kongzue/dbv3/DB.java b/dbv3/src/main/java/com/kongzue/dbv3/DB.java
index 25dcb20..e24e3c0 100644
--- a/dbv3/src/main/java/com/kongzue/dbv3/DB.java
+++ b/dbv3/src/main/java/com/kongzue/dbv3/DB.java
@@ -63,6 +63,11 @@ public static void init(Context context, File dbFile) {
DBHelper.getInstance().init(context, dbFile);
}
+ @Deprecated
+ public static void init(Context context, String DBName, int oldVer) {
+ DBHelper.getInstance().init(context, DBName, oldVer);
+ }
+
/**
* 初始化方法
*
@@ -120,6 +125,57 @@ public boolean add(DBData dbData, boolean allowDuplicate) {
return true;
}
+ /**
+ * 添加新的数据,若 唯一键 存在则更新已有数据
+ *
+ * @param onlyKey 唯一键
+ * @param dbData 要添加的数据
+ * @return 是否添加成功
+ */
+ public boolean addOrUpdate(String onlyKey, DBData dbData) {
+ boolean createFlag = DBHelper.getInstance().createNewTable(tableName, dbData);
+ if (!createFlag) {
+ error("严重错误:创建表失败,表模板" + dbData.getPrintTable());
+ return false;
+ }
+ List findData = DBHelper.getInstance().findData(tableName, new DBData().set(onlyKey, dbData.getString(onlyKey)), SORT.ASC, null, -1, 0);
+ if (findData.isEmpty()) {
+ return add(dbData, false);
+ } else {
+ boolean flag = true;
+ dbData.remove("_id");
+ for (DBData data : findData) {
+ data.putAll(dbData);
+ if (!update(data)) {
+ flag = false;
+ }
+ }
+ return flag;
+ }
+ }
+
+
+ /**
+ * 添加新的数据,若 唯一键 存在则不添加
+ *
+ * @param onlyKey 唯一键
+ * @param dbData 要添加的数据
+ * @return 是否添加成功
+ */
+ public boolean addWhenNon(String onlyKey, DBData dbData) {
+ boolean createFlag = DBHelper.getInstance().createNewTable(tableName, dbData);
+ if (!createFlag) {
+ error("严重错误:创建表失败,表模板" + dbData.getPrintTable());
+ return false;
+ }
+ List findData = DBHelper.getInstance().findData(tableName, new DBData().set(onlyKey, dbData.getString(onlyKey)), SORT.ASC, null, -1, 0);
+ if (findData.isEmpty()) {
+ return add(dbData, false);
+ } else {
+ return false;
+ }
+ }
+
/**
* 修改一个已存在的数据
*
@@ -127,17 +183,17 @@ public boolean add(DBData dbData, boolean allowDuplicate) {
* @return 是否修改成功
*/
public boolean update(DBData dbData) {
- boolean updateFlag = DBHelper.getInstance().update(tableName, dbData);
- if (!updateFlag){
+ boolean updateFlag = DBHelper.getInstance().update(tableName, dbData);
+ if (!updateFlag) {
boolean updateTableFlag = DBHelper.getInstance().updateTable(tableName, dbData);
if (!updateTableFlag) {
error("严重错误:更新表失败,表模板" + dbData.getPrintTable());
return false;
}
- if ( DBHelper.getInstance().update(tableName, dbData)){
+ if (DBHelper.getInstance().update(tableName, dbData)) {
log("表 " + tableName + " 更新数据:" + dbData);
return true;
- }else{
+ } else {
error("严重错误:更新数据失败:" + dbData);
return false;
}
@@ -212,7 +268,7 @@ public boolean delete() {
*
* @return 是否删除成功
*/
- public boolean cleanAll(){
+ public boolean cleanAll() {
return DBHelper.getInstance().delete(tableName, null, null);
}
@@ -221,7 +277,7 @@ public boolean cleanAll(){
*
* @return 是否删除成功
*/
- public boolean deleteTable(){
+ public boolean deleteTable() {
return DBHelper.getInstance().deleteTable(tableName);
}
@@ -274,7 +330,7 @@ public DB subData(long start, long count) {
* @return 继续条件
*/
public DB cleanLimit() {
- limitStart = 0;
+ limitStart = -1;
limitCount = 0;
return this;
}
diff --git a/dbv3/src/main/java/com/kongzue/dbv3/util/DBHelper.java b/dbv3/src/main/java/com/kongzue/dbv3/util/DBHelper.java
index 2e021c0..b32b000 100644
--- a/dbv3/src/main/java/com/kongzue/dbv3/util/DBHelper.java
+++ b/dbv3/src/main/java/com/kongzue/dbv3/util/DBHelper.java
@@ -41,7 +41,27 @@ public void init(Context context, String dbName) {
helper.dbName = dbName;
try {
- SQLiteOpenHelper sqLiteOpenHelper = new SQLiteHelperImpl(context, dbName, 1);
+ SQLiteOpenHelper sqLiteOpenHelper = new SQLiteHelperImpl(context, dbName, oldVer);
+ helper.db = sqLiteOpenHelper.getWritableDatabase();
+ if (db == null) {
+ error("初始化数据库失败");
+ }
+ } catch (Exception e) {
+ if (DEBUGMODE) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ private int oldVer = 1;
+
+ public void init(Context context, String dbName, int oldVer) {
+ helper.context = context;
+ helper.dbName = dbName;
+ helper.oldVer=oldVer;
+
+ try {
+ SQLiteOpenHelper sqLiteOpenHelper = new SQLiteHelperImpl(context, dbName, oldVer);
helper.db = sqLiteOpenHelper.getWritableDatabase();
if (db == null) {
error("初始化数据库失败");
@@ -83,7 +103,7 @@ public SQLiteDatabase getDb() {
}
public boolean isHaveTable(String tableName) {
- synchronized (DBHelper.this) {
+ synchronized (DBHelper.class) {
if (db == null) {
error("警告:数据库未初始化");
return false;
@@ -116,385 +136,408 @@ public boolean isHaveTable(String tableName) {
}
public boolean addData(String tableName, DBData data, boolean allowDuplicate) {
- if (db == null) {
- error("警告:数据库未初始化");
- return false;
- }
- if (!allowDuplicate) {
- if (DBHelper.getInstance().findDataCount(tableName, data, null) != 0) {
- error("重复数据:" + data);
- return true;
+ synchronized (DBHelper.class) {
+ if (db == null) {
+ error("警告:数据库未初始化");
+ return false;
}
- }
- db.beginTransaction();
- try {
- String sql = "INSERT INTO " + tableName + " (";
- Set set = data.keySet();
- for (String key : set) {
- if (!"_id".equals(key)) {
- sql = sql + "\'" + key + "\'" + " ,";
+ if (!allowDuplicate) {
+ if (DBHelper.getInstance().findDataCount(tableName, data, null) != 0) {
+ error("重复数据:" + data);
+ return true;
}
}
- if (sql.endsWith(",")) {
- sql = sql.substring(0, sql.length() - 1);
- }
- sql = sql + ") VALUES (";
- for (String key : set) {
- if (!"_id".equals(key)) {
- String value = data.get(key).toString();
- sql = sql + "\'" + value + "\'" + " ,";
+ db.beginTransaction();
+ try {
+ String sql = "INSERT INTO " + tableName + " (";
+ Set set = data.keySet();
+ for (String key : set) {
+ if (!"_id".equals(key)) {
+ sql = sql + "\'" + key + "\'" + " ,";
+ }
}
+ if (sql.endsWith(",")) {
+ sql = sql.substring(0, sql.length() - 1);
+ }
+ sql = sql + ") VALUES (";
+ for (String key : set) {
+ if (!"_id".equals(key)) {
+ String value = data.get(key).toString();
+ sql = sql + "\'" + value + "\'" + " ,";
+ }
+ }
+ if (sql.endsWith(",")) {
+ sql = sql.substring(0, sql.length() - 1);
+ }
+ sql = sql + ")";
+ log("SQL.exec: " + sql);
+ db.execSQL(sql);
+ db.setTransactionSuccessful(); //设置事务成功完成
+ return true;
+ } catch (Exception e) {
+ if (DEBUGMODE) {
+ e.printStackTrace();
+ }
+ return false;
+ } finally {
+ db.endTransaction(); //结束事务
}
- if (sql.endsWith(",")) {
- sql = sql.substring(0, sql.length() - 1);
- }
- sql = sql + ")";
- log("SQL.exec: " + sql);
- db.execSQL(sql);
- db.setTransactionSuccessful(); //设置事务成功完成
- return true;
- } catch (Exception e) {
- if (DEBUGMODE) {
- e.printStackTrace();
- }
- return false;
- } finally {
- db.endTransaction(); //结束事务
}
}
//创建表
public boolean createNewTable(String tableName, DBData dbData) {
- StringBuffer newTableSQLCommandBuffer = new StringBuffer("CREATE TABLE IF NOT EXISTS " + tableName + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, ");
- Set set = dbData.keySet();
- for (String key : set) {
- if (!"_id".equals(key)) {
- newTableSQLCommandBuffer.append(" " + key + " TEXT,");
+ synchronized (DBHelper.class) {
+ if (isHaveTable(tableName)) {
+ return true;
}
- }
- String newTableSQLCommand = newTableSQLCommandBuffer.toString();
- if (newTableSQLCommand.endsWith(",")) {
- newTableSQLCommand = newTableSQLCommand.substring(0, newTableSQLCommand.length() - 1);
- }
- newTableSQLCommand = newTableSQLCommand + ")";
- log("SQL.exec: " + newTableSQLCommand);
- try {
- if (db != null) {
- db.execSQL(newTableSQLCommand);
+ StringBuffer newTableSQLCommandBuffer = new StringBuffer("CREATE TABLE IF NOT EXISTS " + tableName + " (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT, ");
+ Set set = dbData.keySet();
+ for (String key : set) {
+ if (!"_id".equals(key)) {
+ newTableSQLCommandBuffer.append(" " + key + " TEXT,");
+ }
}
- } catch (Exception e) {
- if (DEBUGMODE) {
- e.printStackTrace();
+ String newTableSQLCommand = newTableSQLCommandBuffer.toString();
+ if (newTableSQLCommand.endsWith(",")) {
+ newTableSQLCommand = newTableSQLCommand.substring(0, newTableSQLCommand.length() - 1);
}
- return false;
+ newTableSQLCommand = newTableSQLCommand + ")";
+ log("SQL.exec: " + newTableSQLCommand);
+ try {
+ if (db != null) {
+ db.execSQL(newTableSQLCommand);
+ }
+ } catch (Exception e) {
+ if (DEBUGMODE) {
+ e.printStackTrace();
+ }
+ return false;
+ }
+ restartDB();
+ return true;
}
- restartDB();
- return true;
}
//更新表
public boolean updateTable(String tableName, DBData dbData) {
- String updateTableSQLCommand = "ALTER TABLE " + tableName + " ADD ";
- List newKeys = new ArrayList<>();
- List oldKeys = getTableAllKeys(tableName);
- for (String key : dbData.keySet()) {
- if (!"_id".equals(key)) {
- if (!oldKeys.contains(key)) {
- newKeys.add(key);
+ synchronized (DBHelper.class) {
+ String updateTableSQLCommand = "ALTER TABLE " + tableName + " ADD ";
+ List newKeys = new ArrayList<>();
+ List oldKeys = getTableAllKeys(tableName);
+ for (String key : dbData.keySet()) {
+ if (!"_id".equals(key)) {
+ if (!oldKeys.contains(key)) {
+ newKeys.add(key);
+ }
}
}
- }
- for (String key : newKeys) {
- updateTableSQLCommand = updateTableSQLCommand + " " + key + " VARCHAR,";
- }
- if (updateTableSQLCommand.endsWith(",")) {
- updateTableSQLCommand = updateTableSQLCommand.substring(0, updateTableSQLCommand.length() - 1);
- }
- log("SQL.exec: " + updateTableSQLCommand);
- try {
- if (db != null) {
- db.execSQL(updateTableSQLCommand);
+ for (String key : newKeys) {
+ updateTableSQLCommand = updateTableSQLCommand + " " + key + " VARCHAR,";
}
- } catch (Exception e) {
- if (DEBUGMODE) {
- e.printStackTrace();
+ if (updateTableSQLCommand.endsWith(",")) {
+ updateTableSQLCommand = updateTableSQLCommand.substring(0, updateTableSQLCommand.length() - 1);
}
- return false;
+ log("SQL.exec: " + updateTableSQLCommand);
+ try {
+ if (db != null) {
+ db.execSQL(updateTableSQLCommand);
+ }
+ } catch (Exception e) {
+ if (DEBUGMODE) {
+ e.printStackTrace();
+ }
+ return false;
+ }
+ restartDB();
+ return true;
}
- restartDB();
- return true;
}
//获取一个表内的所有字段名
private List getTableAllKeys(String tableName) {
- List result = new ArrayList<>();
- Cursor c = null;
- try {
- c = db.rawQuery("SELECT * FROM " + tableName + " WHERE 0", null);
- String[] columnNames = c.getColumnNames();
- for (String s : columnNames) {
- result.add(s);
- }
- } catch (Exception e) {
- if (DEBUGMODE) {
- e.printStackTrace();
+ synchronized (DBHelper.class) {
+ List result = new ArrayList<>();
+ Cursor c = null;
+ try {
+ c = db.rawQuery("SELECT * FROM " + tableName + " WHERE 0", null);
+ String[] columnNames = c.getColumnNames();
+ for (String s : columnNames) {
+ result.add(s);
+ }
+ } catch (Exception e) {
+ if (DEBUGMODE) {
+ e.printStackTrace();
+ }
+ return result;
+ } finally {
+ if (c != null) {
+ c.close();
+ }
}
return result;
- } finally {
- if (c != null) {
- c.close();
- }
}
- return result;
}
//根据查询条件dbData获取一个表内的所有数据
public List findData(String tableName, DBData findConditions, DB.SORT sort, List whereConditions, long start, long count) {
- if (db == null) {
- error("警告:数据库未初始化");
- return new ArrayList<>();
- }
- List result = new ArrayList<>();
- StringBuffer sql = new StringBuffer("SELECT * FROM " + tableName);
- if (findConditions != null || whereConditions != null) {
- sql.append(" where ");
- if (findConditions != null) {
- Set set = findConditions.keySet();
- for (String key : set) {
- String value = findConditions.get(key).toString();
- sql.append(" " + key + " = \'" + value + "\' AND");
- }
+ synchronized (DBHelper.class) {
+ if (db == null) {
+ error("警告:数据库未初始化");
+ return new ArrayList<>();
}
- if (whereConditions != null) {
- for (String condition : whereConditions) {
- condition = condition.trim();
- sql.append(" " + condition + " AND");
+ List result = new ArrayList<>();
+ StringBuffer sql = new StringBuffer("SELECT * FROM " + tableName);
+ if (findConditions != null || whereConditions != null) {
+ sql.append(" where ");
+ if (findConditions != null) {
+ Set set = findConditions.keySet();
+ for (String key : set) {
+ String value = findConditions.get(key).toString();
+ sql.append(" " + key + " = \'" + value + "\' AND");
+ }
+ }
+ if (whereConditions != null) {
+ for (String condition : whereConditions) {
+ condition = condition.trim();
+ sql.append(" " + condition + " AND");
+ }
+ }
+ if (sql.toString().endsWith("AND")) {
+ sql = new StringBuffer(sql.substring(0, sql.length() - 3));
}
}
if (sql.toString().endsWith("AND")) {
sql = new StringBuffer(sql.substring(0, sql.length() - 3));
}
- }
- if (sql.toString().endsWith("AND")) {
- sql = new StringBuffer(sql.substring(0, sql.length() - 3));
- }
- if (sort != null) {
- sql.append(" ORDER BY _id ");
- sql.append(sort.name());
- }
- if (start != -1 && count != 0) {
- sql.append(" limit ");
- sql.append(start);
- sql.append(",");
- sql.append(count);
- }
- log("SQL.exec: " + sql.toString());
- Cursor c = null;
- try {
- c = db.rawQuery(sql.toString(), null);
- while (c.moveToNext()) {
- DBData data = new DBData();
- for (int i = 0; i < c.getColumnCount(); i++) {
- String key = c.getColumnName(i);
- data.set(key, c.getString(c.getColumnIndex(key)));
- }
- result.add(data);
+ if (sort != null) {
+ sql.append(" ORDER BY _id ");
+ sql.append(sort.name());
}
- c.close();
- } catch (Exception e) {
- error("查询错误:" + sql.toString());
- if (DEBUGMODE) {
- e.printStackTrace();
+ if (start != -1 && count != 0) {
+ sql.append(" limit ");
+ sql.append(start);
+ sql.append(",");
+ sql.append(count);
}
- } finally {
- if (c != null) {
+ log("SQL.exec: " + sql.toString());
+ Cursor c = null;
+ try {
+ c = db.rawQuery(sql.toString(), null);
+ while (c.moveToNext()) {
+ DBData data = new DBData();
+ for (int i = 0; i < c.getColumnCount(); i++) {
+ String key = c.getColumnName(i);
+ data.set(key, c.getString(c.getColumnIndex(key)));
+ }
+ result.add(data);
+ }
c.close();
+ } catch (Exception e) {
+ error("查询错误:" + sql.toString());
+ if (DEBUGMODE) {
+ e.printStackTrace();
+ }
+ } finally {
+ if (c != null) {
+ c.close();
+ }
}
+ return result;
}
- return result;
}
//根据查询条件dbData获取一个表内的所有符合条件数据的数量
public long findDataCount(String tableName, DBData findData, List whereConditions) {
- if (db == null) {
- error("警告:数据库未初始化");
- return 0;
- }
- StringBuffer sql = new StringBuffer("SELECT * FROM " + tableName);
- if (findData != null || whereConditions != null) {
- sql.append(" where ");
- if (findData != null) {
- Set set = findData.keySet();
- for (String key : set) {
- String value = findData.get(key).toString();
- sql.append(" " + key + " = \'" + value + "\' AND");
- }
+ synchronized (DBHelper.class) {
+ if (db == null) {
+ error("警告:数据库未初始化");
+ return 0;
}
- if (whereConditions != null) {
- for (String condition : whereConditions) {
- condition = condition.trim();
- sql.append(" " + condition + " AND");
+ StringBuffer sql = new StringBuffer("SELECT * FROM " + tableName);
+ if (findData != null || whereConditions != null) {
+ sql.append(" where ");
+ if (findData != null) {
+ Set set = findData.keySet();
+ for (String key : set) {
+ String value = findData.get(key).toString();
+ sql.append(" " + key + " = \'" + value + "\' AND");
+ }
+ }
+ if (whereConditions != null) {
+ for (String condition : whereConditions) {
+ condition = condition.trim();
+ sql.append(" " + condition + " AND");
+ }
+ }
+ if (sql.toString().endsWith("AND")) {
+ sql = new StringBuffer(sql.substring(0, sql.length() - 3));
}
}
- if (sql.toString().endsWith("AND")) {
- sql = new StringBuffer(sql.substring(0, sql.length() - 3));
- }
- }
- log("SQL.exec: " + sql.toString());
- long count = 0;
- Cursor c = null;
- try {
- c = db.rawQuery(sql.toString(), null);
- c.moveToFirst();
- count = c.getLong(0);
- } catch (Exception e) {
- //此错误忽略不计的原因是为此方法多用于添加前校验是否存在,肯定不存在的情况下这里必然抛异常,此异常完全可以忽略
+ log("SQL.exec: " + sql.toString());
+ long count = 0;
+ Cursor c = null;
+ try {
+ c = db.rawQuery(sql.toString(), null);
+ c.moveToFirst();
+ count = c.getLong(0);
+ } catch (Exception e) {
+ //此错误忽略不计的原因是为此方法多用于添加前校验是否存在,肯定不存在的情况下这里必然抛异常,此异常完全可以忽略
// if (DEBUGMODE) {
// e.printStackTrace();
// }
- } finally {
- if (c != null) {
- c.close();
+ } finally {
+ if (c != null) {
+ c.close();
+ }
}
+ return count;
}
- return count;
}
public long rawCount(String sql) {
- if (db == null) {
- error("警告:数据库未初始化");
- return 0;
- }
- long result = 0;
- Cursor c = null;
- try {
- c = db.rawQuery(sql, null);
- c.moveToFirst();
- result = c.getLong(0);
- } catch (Exception e) {
- } finally {
- if (c != null) {
- c.close();
+ synchronized (DBHelper.class) {
+ if (db == null) {
+ error("警告:数据库未初始化");
+ return 0;
}
+ long result = 0;
+ Cursor c = null;
+ try {
+ c = db.rawQuery(sql, null);
+ c.moveToFirst();
+ result = c.getLong(0);
+ } catch (Exception e) {
+ } finally {
+ if (c != null) {
+ c.close();
+ }
+ }
+ return result;
}
- return result;
}
public boolean delete(String tableName, DBData dbData, List whereConditions) {
- if (db == null) {
- error("警告:数据库未初始化");
- return false;
- }
- if (dbData != null) {
- if (dbData.getInt("_id") == 0) {
- error("只能对已存在的数据(使用find查询出来的数据)进行删除");
+ synchronized (DBHelper.class) {
+ if (db == null) {
+ error("警告:数据库未初始化");
return false;
}
- }
- db.beginTransaction();
- try {
- StringBuffer sql = new StringBuffer("delete from ");
- sql.append(tableName);
- if (dbData != null || whereConditions != null) {
- sql.append(" where ");
- if (dbData != null) {
- sql.append("_id=\'" + dbData.getInt("_id") + "\' AND");
+ if (dbData != null) {
+ if (dbData.getInt("_id") == 0) {
+ error("只能对已存在的数据(使用find查询出来的数据)进行删除");
+ return false;
}
- if (whereConditions != null) {
- for (String condition : whereConditions) {
- condition = condition.trim();
- sql.append(" " + condition + " AND");
+ }
+ db.beginTransaction();
+ try {
+ StringBuffer sql = new StringBuffer("delete from ");
+ sql.append(tableName);
+ if (dbData != null || whereConditions != null) {
+ sql.append(" where ");
+ if (dbData != null) {
+ sql.append("_id=\'" + dbData.getInt("_id") + "\' AND");
+ }
+ if (whereConditions != null) {
+ for (String condition : whereConditions) {
+ condition = condition.trim();
+ sql.append(" " + condition + " AND");
+ }
+ }
+ if (sql.toString().endsWith("AND")) {
+ sql = new StringBuffer(sql.substring(0, sql.length() - 3));
}
+ } else {
+ db.execSQL("update sqlite_sequence set seq=0 where name='" + tableName + "';"); //将自增键初始化为0
}
- if (sql.toString().endsWith("AND")) {
- sql = new StringBuffer(sql.substring(0, sql.length() - 3));
+ log("SQL.exec: " + sql.toString());
+ db.execSQL(sql.toString());
+ db.setTransactionSuccessful(); //设置事务成功完成
+ } catch (Exception e) {
+ if (DEBUGMODE) {
+ e.printStackTrace();
}
- } else {
- db.execSQL("update sqlite_sequence set seq=0 where name='" + tableName + "';"); //将自增键初始化为0
- }
- log("SQL.exec: " + sql.toString());
- db.execSQL(sql.toString());
- db.setTransactionSuccessful(); //设置事务成功完成
- } catch (Exception e) {
- if (DEBUGMODE) {
- e.printStackTrace();
+ return false;
+ } finally {
+ db.endTransaction(); //结束事务
}
- return false;
- } finally {
- db.endTransaction(); //结束事务
+ return true;
}
- return true;
}
public boolean update(String tableName, DBData dbData) {
- if (db == null) {
- error("警告:数据库未初始化");
- return false;
- }
- if (dbData.getInt("_id") == 0) {
- error("只能对已存在的数据(使用find查询出来的数据)进行修改");
- return false;
- }
- db.beginTransaction();
- try {
- String sql = "update " + tableName + " set ";
- Set set = dbData.keySet();
- for (String key : set) {
- if (!"_id".equals(key)) {
- String value = dbData.getString(key);
- sql = sql + " " + key + " = \'" + value + "\' ,";
- }
+ synchronized (DBHelper.class) {
+ if (db == null) {
+ error("警告:数据库未初始化");
+ return false;
}
- if (sql.endsWith(",")) {
- sql = sql.substring(0, sql.length() - 1);
+ if (dbData.getInt("_id") == 0) {
+ error("只能对已存在的数据(使用find查询出来的数据)进行修改");
+ return false;
}
- sql = sql + " where _id=\"" + dbData.getInt("_id") + "\"";
- log("SQL.exec: " + sql);
- db.execSQL(sql);
- db.setTransactionSuccessful();
- } catch (Exception e) {
- if (DEBUGMODE) {
- e.printStackTrace();
+ db.beginTransaction();
+ try {
+ String sql = "update " + tableName + " set ";
+ Set set = dbData.keySet();
+ for (String key : set) {
+ if (!"_id".equals(key)) {
+ String value = dbData.getString(key);
+ sql = sql + " " + key + " = \'" + value + "\' ,";
+ }
+ }
+ if (sql.endsWith(",")) {
+ sql = sql.substring(0, sql.length() - 1);
+ }
+ sql = sql + " where _id=\"" + dbData.getInt("_id") + "\"";
+ log("SQL.exec: " + sql);
+ db.execSQL(sql);
+ db.setTransactionSuccessful();
+ } catch (Exception e) {
+ if (DEBUGMODE) {
+ e.printStackTrace();
+ }
+ return false;
+ } finally {
+ db.endTransaction();
}
- return false;
- } finally {
- db.endTransaction();
+ return true;
}
- return true;
}
public boolean deleteTable(String tableName) {
- if (db == null) {
- error("警告:数据库未初始化");
- return false;
- }
- if (!isHaveTable(tableName)) {
- log("不存在要删除的表:" + tableName);
- return true;
- }
- db.beginTransaction();
- try {
- String sql = "drop table " + tableName;
- log("SQL.exec: " + sql);
- db.execSQL(sql);
- db.execSQL("update sqlite_sequence set seq=0 where name='" + tableName + "';"); //将自增键初始化为0
- db.setTransactionSuccessful();
- } catch (Exception e) {
- if (DEBUGMODE) {
- e.printStackTrace();
+ synchronized (DBHelper.class) {
+ if (db == null) {
+ error("警告:数据库未初始化");
+ return false;
}
- return false;
- } finally {
- db.endTransaction();
+ if (!isHaveTable(tableName)) {
+ log("不存在要删除的表:" + tableName);
+ return true;
+ }
+ db.beginTransaction();
+ try {
+ String sql = "drop table " + tableName;
+ log("SQL.exec: " + sql);
+ db.execSQL(sql);
+ db.execSQL("update sqlite_sequence set seq=0 where name='" + tableName + "';"); //将自增键初始化为0
+ db.setTransactionSuccessful();
+ } catch (Exception e) {
+ if (DEBUGMODE) {
+ e.printStackTrace();
+ }
+ return false;
+ } finally {
+ db.endTransaction();
+ }
+ return true;
}
- return true;
}
private class SQLiteHelperImpl extends SQLiteOpenHelper {
public SQLiteHelperImpl(Context context, String dbName, int dbVersion) {
//CursorFactory设置为null,使用默认值
- super(context, dbName + ".db", null, dbVersion + 1);
+ super(context, dbName + ".db", null, dbVersion == 0 ? dbVersion + 1 : dbVersion);
}
@Override
@@ -538,7 +581,7 @@ public void restartDB() {
db.close();
}
db = null;
- SQLiteOpenHelper sqLiteOpenHelper = new SQLiteHelperImpl(context, dbName, 1);
+ SQLiteOpenHelper sqLiteOpenHelper = new SQLiteHelperImpl(context, dbName, oldVer);
db = sqLiteOpenHelper.getWritableDatabase();
}
}