SQLiteOpenHelper主要用於 創建數據庫
SQLiteDatabase 主要用於 執行sql語句
- 程序內使用SQLite數據庫是通過SQLiteOpenHelper進行操作
- 1. 自己寫個類繼承SQLiteOpenHelper,重寫以下3個方法
- public void onCreate(SQLiteDatabase db)
- {//創建數據庫時的操作,如建表}
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
- {
- //版本更新的操作
- }
- 2. 通過SQLiteOpenHelper的getWritableDatabase()獲得一個SQLiteDatabase數據庫,以后的操作都是對SQLiteDatabase進行操作。
- 3. 對得到的SQLiteDatabase對象進行增,改,刪,查等操作。
- 代碼
- package cx.myNote;
- import android.content.ContentValues;
- import android.content.Context;
- import android.content.Intent;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- //DBOptions for login
- public class DBOptions {
- private static final String DB_NAME = "notes.db";
- private static final String DB_CREATE="create table logininf(name text,pwd text)";
- public class DBHelper extends SQLiteOpenHelper
- {
- public DBHelper(Context context) {
- super(context,DB_NAME, null, 1);
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- // TODO Auto-generated method stub
- //建表
- db.execSQL(DB_CREATE);
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- // TODO Auto-generated method stub
- db.execSQL("drop table if exists logininf");
- onCreate(db);
- }
- }
- private Context context;
- private SQLiteDatabase db;
- private DBHelper dbHelper;
- public DBOptions(Context context)
- {
- this.context = context;
- dbHelper = new DBHelper(context);
- db=dbHelper.getReadableDatabase();
- }
- //自己寫的方法,對數據庫進行操作
- public String getName()
- {
- Cursor cursor = db.rawQuery("select name from logininf", null);
- cursor.moveToFirst();
- return cursor.getString(0);
- }
- public int changePWD(String oldP,String pwd)
- {
- ContentValues values = new ContentValues();
- values.put("pwd", pwd);
- return db.update("logininf", values,"pwd="+oldP, null);
- }
- }
insert方法插入的一行記錄使用ContentValus存放,ContentValues類似於Map,它提供了put(String key, Xxx value)(其中key為數據列的列名)方法用於存入數據、getAsXxxx(String key)方法用於取出數據。
轉載自 http://blog.csdn.net/wangqilin8888/article/details/7780228