public class DBTableOperate {
private final String TAG = "nan";
private static DBTableOperate mInstance;
private DBTableOperate() {
}
public static DBTableOperate getInstance() {
if (null == mInstance) {
synchronized (DBTableOperate.class) {
if (null == mInstance) {
mInstance = new DBTableOperate();
}
}
}
return mInstance;
}
public synchronized void columnAdd(SQLiteDatabase db, String tableName,
String columnName, String columnType,
Object defaultField) {
try {
if (null != db) {
Cursor c = db.rawQuery(String.format(Locale.CHINESE, "SELECT * FROM %s LIMIT 1 ", tableName), null);
boolean flag = true;
if (c != null) {
for (int i = 0; i < c.getColumnCount(); i++) {
if (columnName.equalsIgnoreCase(c.getColumnName(i))) {
flag = false;
break;
}
}
if (flag) {
db.execSQL(String.format(Locale.CHINESE, "ALTER TABLE %s ADD COLUMN %s %s default %s", tableName, columnName, columnType, defaultField));
}
c.close();
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, String.format(Locale.CHINESE, "表:%s 中 %s 列添加失败==%s", tableName, columnName, e.getMessage()));
}
}
public synchronized void tableRename(SQLiteDatabase db, String oldTableName, String newTableName) {
try {
db.execSQL(String.format(Locale.CHINESE, "ALTER TABLE %s RENAME TO %s", oldTableName, newTableName));
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, String.format(Locale.CHINESE, "表:%s 更新名称为 %s 失败==%s", oldTableName, newTableName, e.getMessage())
);
}
}
public synchronized void deleteTable(SQLiteDatabase db, String tableName) {
try {
db.execSQL(String.format(Locale.CHINESE, "DROP TABLE %s", tableName));
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, String.format(Locale.CHINESE, "表:%s 删除失败==%s", tableName, e.getMessage())
);
}
}
public synchronized void tablePragma(SQLiteDatabase db, String tableName) {
try {
db.execSQL(String.format(Locale.CHINESE, "PRAGMA TABLE_INFO (%s)", tableName));
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, String.format(Locale.CHINESE, "表:%s 结构查询失败==%s", tableName, e.getMessage())
);
}
}
public synchronized void columnDelete(SQLiteDatabase db, ConnectionSource connectionSource, String tableName, Class classz, String... retain) {
try {
String tableNameSuffix = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date(System.currentTimeMillis()));
String tempTableName = String.format(Locale.CHINESE, "%s_%s", tableName, tableNameSuffix);
tableRename(db, tableName, tempTableName);
TableUtils.createTableIfNotExists(connectionSource, classz);
StringBuffer buffer = new StringBuffer();
for (String filed : retain) {
buffer.append(filed + ",");
}
String fileds = buffer.substring(0, buffer.length() - 1);
db.execSQL(String.format(Locale.CHINESE, "INSERT INTO %s (%s) SELECT %s FROM %s", tableName, fileds, fileds, tempTableName));
deleteTable(db, tempTableName);
} catch (Exception e) {
e.printStackTrace();
Log.e("nan", "删除表中指定列失败====" + e.getMessage());
}
}}