package cn.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseAdapter {
private Context mCtx=null;
private DatabaseHelper dbHelper;
private SQLiteDatabase db=null;
private static final String DATABASE_NAME="accountant.db";
private static final int DATABASE_VERSION=1;
private static final String DATABASE_CREATE_1="CREATE TABLE 'aa' "
public DatabaseAdapter(Context mCtx){
this.mCtx=mCtx;
}
public DatabaseAdapter open()throws SQLException{
dbHelper=new DatabaseHelper(mCtx);
db=dbHelper.getWritableDatabase();
return this;
}
public void close(){
dbHelper.close();
}
/**
* 查询所有数据
* @param TableName 表名
* @param cols 查询列名数组
* @return
*/
public Cursor getAll(String TableName , String[] cols){
return db.query(TableName, cols, null, null, null, null, null);
}
/**
* 查询所有数据
* @param TableName 表名
* @param cols 查询列名数组
* @return
*/
public Cursor getByParams(String TableName , String[] cols , String selection , String[] selectionArgs){
return db.query(TableName, cols, selection, selectionArgs, null, null, null);
}
/**
* 添加数据
* @param note
* @return
*/
public long create(String TableName , ContentValues args){
return db.insert(TableName, null, args);
}
/**
* 删除数据
* @param TableName 表名
* @param rowId Id
* @return
*/
public boolean delete(String TableName , long rowId){
return db.delete(TableName, "id = " +rowId, null)>0;
}
/**
* 更新数据
* @param TableName 表名
* @param rowId id
* @param args 数据集
* @return
*/
public boolean update(String TableName , long rowId,ContentValues args){
return db.update(TableName, args, "id = "+rowId, null)>0;
}
/**
* 按照ID查询数据
* @param TableName 表名
* @param rowId ID
* @param cols 列名数组
* @return
* @throws SQLException
*/
public Cursor get(String TableName , long rowId , String[] cols)throws SQLException{
Cursor mCursor=db.query(true, TableName, cols, "id = "+rowId, null, null, null, null, null);
if(mCursor!=null){
mCursor.moveToFirst();
}
return mCursor;
}
/**
* 按照SQL语句查询数据
* @param sql sql语句
* @param args 参数值
* @return
*/
public Cursor getBySQL(String sql , String[] args){
Cursor mCursor = db.rawQuery(sql, args);
return mCursor;
}
/**
* 关闭数据库连接
*/
public void closeDB(){
if(db!= null || db.isOpen()){
db.close();
}
}
/**
* 打开数据库连接
*/
public void openDB(){
if(db == null || !db.isOpen()){
db=dbHelper.getWritableDatabase();
}
}
private static class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_1);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
android SQLite数据库应用
最新推荐文章于 2024-11-15 22:11:31 发布