Android之SQLite学习
我们在使用SQLite的时候,一般都是直接封装一个SQLiteOpenHelper类,然后对类进行操作,所以这里我主要讲一下如何使用SQLiteOpenHelper。
package com.android.liu.sqlite;
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 MyDataBaseHelper {
public static final String TAG="MyDataBaseHelper";
public static final String KEY_ID="_id";
public static final String KEY_USERNAME="username";
public static final String KEY_SEX="sex";
public static final String DB_NAME="user.db";
public static final String DB_TABLE="userTbl";
public static final int DB_VERSION=1;
public static final String DB_CREATE= "CREATE TABLE "+ DB_TABLE+" ("+ KEY_ID+" INTEGER PRIMARY KEY,"+KEY_USERNAME+" TEXT"+KEY_SEX+" TEXT)";
private Context mContext=null;
private SQLiteDatabase mSQLiteDatabase=null;
private DatabaseHelper mDatabaseHelper=null;
private static class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP DB_TABLE IF EXISTS NOTES");
onCreate(db);
}};
public MyDataBaseHelper(Context context)
{
mContext=context;
}
public void open() throws SQLException
{
mDatabaseHelper=new DatabaseHelper(mContext);
mSQLiteDatabase=mDatabaseHelper.getWritableDatabase();
}
public void close()
{
mDatabaseHelper.close();
}
/**插入一条数据*/
public long insertData(int num,String data,String sex)
{
ContentValues initialValues=new ContentValues();
initialValues.put(KEY_ID, num);
initialValues.put(KEY_USERNAME, data);
initialValues.put(KEY_SEX, sex);
return mSQLiteDatabase.insert(DB_TABLE, KEY_ID, initialValues);
}
/**删除一条数据*/
public boolean deleteData(long rowId)
{
return mSQLiteDatabase.delete(DB_TABLE, KEY_ID+"="+rowId,null)>0;
}
/**
* 查询所有数据
* */
public Cursor fetchAllData()
{
return mSQLiteDatabase.query(DB_TABLE, new String[]{KEY_ID,KEY_USERNAME,KEY_SEX},null,null,null,null,null);
}
/**查询指定数据*/
public Cursor fetchData(long rowId) throws SQLException
{
Cursor mCursor=mSQLiteDatabase.query(true, DB_TABLE, new String[]{KEY_ID,KEY_USERNAME,KEY_SEX}, KEY_ID+"="+rowId,null,null,null,null,null);
if(mCursor!=null)
{
mCursor.moveToFirst();
}
return mCursor;
}
/**
* 更新一条数据*/
public boolean updateData(long rowId,String username,String sex)
{
ContentValues args=new ContentValues();
args.put(KEY_USERNAME, username);
args.put(KEY_SEX, sex);
return mSQLiteDatabase.update(DB_TABLE, args, KEY_ID+"="+rowId, null)>0;
}
}