package com.gzsibu.mobilesibu.d_authorization;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* 操作SQLite数据类
* @author
*
*/
@SuppressLint("NewApi")
public class RecordDB extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "RECORDS.db";
private final static int DATABASE_VERSION = 2;
private int tableCount; //表数量
private String table1; //表名1
private String table2; //表名2
private String table3; //表名3
private String table4; //表名4
public final static String RECORD_ID = "record_id";
public final static String RECORD_CONTENT = "record_content";
/**
* 构造方法,new时回调
* @param context
*/
public RecordDB(Context context,int tableCount) {
//创建sqlite库和标注库版本
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.tableCount = tableCount;
}
/**
* 该函数是在第一次创建的时候执行(创建表)
*/
@Override
public void onCreate(SQLiteDatabase db) {
Log.e("TAG", "---aa22---");
//创建4个表
for(int i=0;i<tableCount;i++){
String sql = "CREATE TABLE " + ("table"+i) + " ("
+ RECORD_ID + " INTEGER primary key autoincrement, "
+ RECORD_CONTENT + " text"+");";
Log.e("TAG", sql);
db.execSQL(sql); //创建books_table表
}
}
/**
* 数据库升级时回调
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
for(int i=0;i<tableCount;i++){
//如果存在表则删除
String sql = "DROP TABLE IF EXISTS " + ("table"+i);
db.execSQL(sql);
}
onCreate(db);
}
//查询数据库记录,返回游标
public Cursor select(String table) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(table, null, null, null, null, null, null);
return cursor;
}
//增加操作
public long insert(String recordContent,String table) {
SQLiteDatabase db = this.getWritableDatabase(); //打开与数据库的连接
ContentValues cv = new ContentValues();
cv.put(RECORD_CONTENT, recordContent);
long row = db.insert(table, null, cv); //插入的内容
return row;
}
//删除操作
public void delete(int id,String table) {
SQLiteDatabase db = this.getWritableDatabase();
String where = RECORD_ID + " = ?";
String[] whereValue ={ Integer.toString(id) };
db.delete(table, where, whereValue);
}
//修改操作
public void update(int id, String recordContent,String table){
SQLiteDatabase db = this.getWritableDatabase();
String where = RECORD_ID + " = ?";
String[] whereValue = { Integer.toString(id) };
ContentValues cv = new ContentValues();
cv.put(RECORD_CONTENT, recordContent);
db.update(table, cv, where, whereValue);
}
}
注:在别的地方通过该类操作数据库时,只需要实例化该类对象并调用其中的操作方法即可,如下:
RecordDB recordDB = new RecordDB(this, 4); //4个表
mCursor = recordDB.select("table"+account_type);//对应表查询