Android SQLiteDatabase的使用
程序员文章站
2024-03-24 15:53:04
...
package com.shawn.test;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseAdapter{
private static final String DB_NAME = "Test.db"; //数据库名
private static final int DB_VERSION = 1; //数据库版本
private static final String DB_TABLE = "my_order"; //表名
private static final String KEY_ID = "_id"; //id
private static final String KEY_ORDER_ID = "order_id"; //订单号
private static final String KEY_TYPE = "_type"; //订单类型
private static final String KEY_STATE = "_state"; //订单状态
private Context context;
private DatabaseHelper mDatabaseHelper;
private SQLiteDatabase mSQLiteDatabase;
private static class DatabaseHelper extends SQLiteOpenHelper{
//创建数据库语句
private static final String DB_CREAT = "CREATE TABLE "
+ DB_TABLE
+ " (" + KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_ORDER_ID + " TEXT,"
+ KEY_TYPE + " INTEGER,"
+ KEY_STATE + " INTEGER)";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null , DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DB_CREAT);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+DB_TABLE);
onCreate(db);
}
}
public DatabaseAdapter(Context context) {
this.context = context;
}
//开启
public void open() {
mDatabaseHelper = new DatabaseHelper(context);
mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();
}
//关闭
public void close() {
mSQLiteDatabase.close();
mDatabaseHelper.close();
}
//增
public long insertData(String orderId, int type) {
ContentValues values = new ContentValues();
values.put(KEY_ORDER_ID, orderId);
values.put(KEY_TYPE, type);
values.put(KEY_STATE, Config.STATE_APPLY);
long id = mSQLiteDatabase.insert(DB_TABLE, KEY_ID, values);
return id;
}
//删
public boolean deleteData(Context context, long id) {
boolean delete = mSQLiteDatabase.delete(DB_TABLE, KEY_ID + "=" +id, null)>0;
return delete;
}
//改
public boolean updateData(long id, int state) {
ContentValues values = new ContentValues();
values.put(KEY_STATE, ""+state);
boolean update = mSQLiteDatabase.update(DB_TABLE, values, KEY_ID + "=" +id, null)>0;
return update;
}
//查
public Cursor fetchData(String selection) {
Cursor mCursor = mSQLiteDatabase.query(DB_TABLE, new String[]{KEY_ID, KEY_ORDER_ID, KEY_TYPE, KEY_STATE}, selection, null, null, null, null);
if(mCursor != null)
mCursor.moveToFirst();
return mCursor;
}
}
上一篇: 1270: 折线分割平面