DbAdapter 创建数据库及初始化 范例

来源:互联网 发布:淘宝一千零一夜2 编辑:程序博客网 时间:2024/06/05 23:45
package com.ibm.bmcc.moa.training.db;import java.util.ArrayList;import java.util.List;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class DBAdapter {private class DBHelper extends SQLiteOpenHelper{/** * 下载列表,所有下载 */public static final String CREATE_TABLE_EXTRAS = "CREATE TABLE IF NOT EXISTS EXTRAS (" +"_id integer primary key autoincrement, " +"url text unique," +"bid text," + //所属模块id"name text," +"size text," +"path text," +"type text," +//类型"createtTime DATETIME DEFAULT (datetime('now', 'localtime')) " +");";public static final String CREATE_TABLE_NEWS = "CREATE TABLE IF NOT EXISTS NEWS (" +"_id integer primary key autoincrement, " +"imgUrl text," +"newId text unique," + //所属模块id"newName text," +"content text," +"path text," +"type text," +//类型"state text," +//类型"createtime DATETIME DEFAULT (datetime('now', 'localtime')) " +");";//记录学习时间的数据库public static final String CREATE_TABLE_STUDYTIME = "CREATE TABLE IF NOT EXISTS STUDYTIME (" +"_id integer primary key autoincrement, " +"userName text," +"className text ," + //课程名称"classId text," +"studyTime text," +"createtime DATETIME DEFAULT (datetime('now', 'localtime')) " +");";public DBHelper(Context context) {super(context, "TRAINING", null, 1);}@Overridepublic void onCreate(SQLiteDatabase db) {String[] tables = {CREATE_TABLE_EXTRAS,CREATE_TABLE_NEWS,CREATE_TABLE_STUDYTIME};for(String sql : tables){try {db.execSQL(sql);} catch (Exception e) {System.out.println(e.getMessage());}}}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {List<List<String>> sqlList = getUpgradeList();for(int i = oldVersion-1;i<newVersion-1;i++){List<String> sqls = sqlList.get(i);for(String sql : sqls){db.execSQL(sql);}}}public List<List<String>> getUpgradeList(){List<List<String>> result = new ArrayList<List<String>>();result.add(getUpgradeSql_1());result.add(getUpgradeSql_2());return result;}public List<String> getUpgradeSql_1(){List<String> sqls = new ArrayList<String>();return sqls;}public List<String> getUpgradeSql_2(){List<String> sqls = new ArrayList<String>();return sqls;}}    private static DBAdapter instance;private DBHelper dbHelper;private Context _context;private SQLiteDatabase _db;private DBAdapter(Context context){        if (instance != null) {            throw new IllegalStateException("A DBAdapter is already running");        }        instance = this;_context = context;dbHelper = new DBHelper(_context);_db = dbHelper.getWritableDatabase();}    public static DBAdapter getInstance(Context context) {        if (instance == null) {            synchronized (DBAdapter.class) {                instance = new DBAdapter(context);            }        }        return instance;    }public void execSQL(String sql) {if(!_db.isOpen()) _db = dbHelper.getWritableDatabase();_db.execSQL(sql);}public void execSQL(String sql, Object[] bindArgs) {if(!_db.isOpen()) _db = dbHelper.getWritableDatabase();_db.execSQL(sql, bindArgs);}/** * Convenience method for inserting a row into the database. * @param table the table to insert the row into * @param nullColumnHack SQL doesn't allow inserting a completely empty row, so if initialValues is empty this column will explicitly be assigned a NULL value * @param values this map contains the initial column values for the row. The keys should be the column names and the values the column values * @return the row ID of the newly inserted row, or -1 if an error occurred */public long insert(String table, String nullColumnHack, ContentValues values) {if(!_db.isOpen())_db = dbHelper.getWritableDatabase();return _db.insert(table, nullColumnHack, values);}/** * Convenience method for updating rows in the database * @param table the table to update in * @param values a map from column names to new column values. null is a valid value that will be translated to NULL. * @param whereClause the optional WHERE clause to apply when updating. Passing null will update all rows. * @param whereArgs * @return the number of rows affected */public long update(String table, ContentValues values, String whereClause, String[] whereArgs) {if(!_db.isOpen())_db = dbHelper.getWritableDatabase();return _db.update(table, values, whereClause, whereArgs);}/** * Convenience method for deleting rows in the database. * @param table the table to delete from * @param whereClause the optional WHERE clause to apply when deleting. Passing null will delete all rows. * @param whereArgs * @return the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause. */public long delete(String table,String whereClause, String[] whereArgs) {if(!_db.isOpen())_db = dbHelper.getWritableDatabase();return _db.delete(table, whereClause, whereArgs);}public Cursor rawQuery(String sql, String[] bindArgs) {if(!_db.isOpen()) _db = dbHelper.getWritableDatabase();return _db.rawQuery(sql, bindArgs);}/** * Query the given table, returning a Cursor over the result set. * @param table The table name to compile the query against. * @param columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used. * @param selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table. * @param selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings. * @param groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped. * @param having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used. * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered. * @return A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details. */public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy){if(!_db.isOpen()) _db = dbHelper.getWritableDatabase();return _db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);}public void close() {if(_db.isOpen())_db.close();}public SQLiteDatabase getDatabase() {if(!_db.isOpen()) _db = dbHelper.getWritableDatabase();return _db;}public void beginTransaction() {if(!_db.isOpen()) _db = dbHelper.getWritableDatabase();_db.beginTransaction();}public void setTransactionSuccessful() {if(!_db.isOpen()) _db = dbHelper.getWritableDatabase();_db.setTransactionSuccessful();}public void endTransaction() {if(!_db.isOpen()) _db = dbHelper.getWritableDatabase();_db.endTransaction();}public Context get_context() {return _context;}}



public class TrainingApplication extends Application {public String storeNum;private static String userCode;private BookCar car;private ViewManager mManager;private DownloadManager mDownloadManager;private static DBAdapter db;public ScreenManager screenManager = null;private static TrainingApplication instance;public static boolean hasNewsFragment = false;public static boolean onStudying = false;public static TrainingApplication getInstance() {return instance;}@Overridepublic void onCreate() {super.onCreate();//TrainingHandler.getInstance().init();instance = this;mDownloadManager = new DownloadManagerImpl(this);db = DBAdapter.getInstance(this);}public synchronized ViewManager getViewManager() {if (mManager == null)mManager = new ViewManager();return mManager;}public static String getAppId() {return appId;}public void setCar(BookCar car) {this.car = car;System.out.println("setCar execute");try {String bookString = car.toXmlString();Tools.writeObject(this, bookString, Constants.BOOKCAR);} catch (Exception e) {e.printStackTrace();}}public synchronized BookCar getBookCar() {System.out.println("getBookCar execute");if (car == null) {try {String bookString = (String) Tools.readObject(this, Constants.BOOKCAR);ArrayList<BookInfo> books = ParseResponse.parseBookList(bookString);car = new BookCar();car.setBooks(books);} catch (Exception e) {e.printStackTrace();}}LogUtil.d("getBookCar execute car is null?" + car/* == null*/);if (car == null) {car = new BookCar();}return car;}public static void setAppId(String appId) {TrainingApplication.appId = appId;}public String getBookUrl() {return Constants.BOOK_ADDRESS;}public static String getUserCode() {return userCode;}public static void setUserCode(String userCode) {TrainingApplication.userCode = userCode;}/** * expTypeList,wareTimeList,appertainList *  * @return */public HashMap<String, HashMap<String, String>> getDataParam() {return dataParam;}public void setDataParam(HashMap<String, HashMap<String, String>> dataParam) {this.dataParam = dataParam;}public List<BookWare> getWareList() {if (wareList == null)wareList = new ArrayList<BookWare>();return wareList;}public void setWareList(List<BookWare> wareList) {this.wareList = wareList;}public String getRequestUrl() {return Constants.SERVER_URL;}public static String getBookUserCode() {return getUserCode();}public DownloadManager getDownloadManager() {return mDownloadManager;}public static DBAdapter getDBAdapter() {return db;}public void showMessage(CharSequence text) {Toast.makeText(this, text, Toast.LENGTH_SHORT).show();}}





0 0
原创粉丝点击