標籤:
1、首先寫一個類繼承自SQLiteOpenHelper
public class DBHelper extends SQLiteOpenHelper{ private static final int DATABASE_VERSION = 1; //資料庫版本號碼 private static final String DATABASE_NAME = ""; //資料庫名稱 public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String sql = ""; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }}
2、需要一個資料庫管理類,比如插入、刪除等
public abstract class DBDao{ private Context context; private DBHelper dbhelper; public SQLiteDatabase sqlitedatabase; public DBDao(Context context) { super(); this.context = context; } /** * 開啟資料庫連接 */ public void openDB(Context context) { dbhelper = new DBHelper(context); sqlitedatabase = dbhelper.getWritableDatabase(); } /** * 關閉資料庫連接 */ public void closeDB(Context context) { if (sqlitedatabase.isOpen()) { sqlitedatabase.close(); } } /** * 更新資料 */ public int updata(String table_name, ContentValues values, int id) { openDB(context); int update = sqlitedatabase.update(table_name, values, "_id=?", new String[]{String.valueOf(id)}); closeDB(context); return update; } /** * 插入資料 */ public void insert(String table_name, ContentValues values) { openDB(context); sqlitedatabase.insert(table_name, null, values); closeDB(context); } /** * 根據唯一標示_id刪除資料 */ public void delete(String table_name, int id) { openDB(context); try { sqlitedatabase.delete(table_name, "_id=?", new String[]{String.valueOf(id)}); } catch (Exception e) { e.printStackTrace(); } finally { closeDB(context); } } /** * 查詢資料 */ public void search(String table_name, int id) { SQLiteDatabase database = dbhelper.getReadableDatabase(); String sql = "select * from " + table_name + " where _id = ?"; Cursor cursor = database.rawQuery(sql, new String[]{String.valueOf(id)}); }}
SQLite協助類