Android項目中如何在一個數(shù)據(jù)庫里建立多張表,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
創(chuàng)新互聯(lián)建站自2013年起,先為額濟(jì)納等服務(wù)建站,額濟(jì)納等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為額濟(jì)納企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
一,創(chuàng)建一個公共的DBAdapter;
為了在整個程序運(yùn)行期間調(diào)用該公共的數(shù)據(jù)庫,我們定義了一個擴(kuò)展自Application的CommDB類:
1,創(chuàng)建唯一的數(shù)據(jù)庫:
1 public class CommDB { 2 3 public static final String DATABASE_NAME = "myDatabase"; //數(shù)據(jù)庫名稱 4 5 public static final int DATABASE_VERSION = 1; 6 //創(chuàng)建該數(shù)據(jù)庫下學(xué)生表的語句 7 private static final String CREATE_TABLE_Students = 8 "CREATE TABLE if not exists " + StudentDB.SQLITE_TABLE + " (" + 9 StudentDB.KEY_ROWID + " integer PRIMARY KEY autoincrement," +10 StudentDB.KEY_AGE + "," +11 StudentDB.KEY_GENDER + "," +12 StudentDB.KEY_NAME + "," +13 " UNIQUE (" + StudentDB.KEY_NAME +"));";//暫時規(guī)定不能重名14 //創(chuàng)建該數(shù)據(jù)庫下教師表的語句15 private static final String CREATE_TABLE_Teachers =16 "CREATE TABLE if not exists " + TeacherDB.SQLITE_TABLE + " (" +17 TeacherDB.KEY_ROWID + " integer PRIMARY KEY autoincrement," +18 TeacherDB.KEY_AGE + "," +19 TeacherDB.KEY_GENDER + "," +20 TeacherDB.KEY_NAME + "," +21 " UNIQUE (" + TeacherDB.KEY_AGE +"));";22 private final Context context; 23 private DatabaseHelper DBHelper;24 private SQLiteDatabase db;25 /**26 * Constructor27 * @param ctx28 */29 public CommDB(Context ctx)30 {31 this.context = ctx;32 this.DBHelper = new DatabaseHelper(this.context);33 }34 35 private static class DatabaseHelper extends SQLiteOpenHelper 36 {37 DatabaseHelper(Context context) 38 {39 super(context, DATABASE_NAME, null, DATABASE_VERSION);40 }41 42 @Override43 public void onCreate(SQLiteDatabase db) 44 {45 db.execSQL(CREATE_TABLE_Students);//創(chuàng)建學(xué)生表46 db.execSQL(CREATE_TABLE_Teachers);//創(chuàng)建教師表 47 }48 49 @Override50 public void onUpgrade(SQLiteDatabase db, int oldVersion, 51 int newVersion) 52 { 53 // Adding any table mods to this guy here54 }55 } 56 57 /**58 * open the db59 * @return this60 * @throws SQLException61 * return type: DBAdapter62 */63 public CommDB open() throws SQLException 64 {65 this.db = this.DBHelper.getWritableDatabase();66 return this;67 }68 69 /**70 * close the db 71 * return type: void72 */73 public void close() 74 {75 this.DBHelper.close();76 }77 }
2,在app開始運(yùn)行時,創(chuàng)建上述的數(shù)據(jù)庫,并創(chuàng)建對應(yīng)的數(shù)據(jù)表:
1 public class GApplication extends Application { 2 private CommDB comDBHelper; 3 4 @Override 5 public void onCreate() { 6 // TODO Auto-generated method stub 7 super.onCreate(); 8 comDBHelper = new CommDB(this); 9 comDBHelper.open();10 }11 12 }
二,分別創(chuàng)建對應(yīng)的數(shù)據(jù)表;
1,建立學(xué)生數(shù)據(jù)表類:
public class StudentDB {public static final String KEY_ROWID = "_id";public static final String KEY_AGE = "age";public static final String KEY_GENDER = "gender";public static final String KEY_NAME = "name";private static final String TAG = "StudentDbAdapter";private DatabaseHelper mDbHelper;private SQLiteDatabase mDb; // private static final String DATABASE_NAME = "Fortrun_Ticket11";static final String SQLITE_TABLE = "StudentTable";private final Context mCtx;private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) {super(context, CommDB.DATABASE_NAME, null, CommDB.DATABASE_VERSION); } @Overridepublic void onCreate(SQLiteDatabase db) { } @Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE); onCreate(db); } }public StudentDB(Context ctx) {this.mCtx = ctx; }public StudentDB open() throws SQLException { mDbHelper = new DatabaseHelper(mCtx); mDb = mDbHelper.getWritableDatabase();return this; }public void close() {if (mDbHelper != null) { mDbHelper.close(); } }/** * 創(chuàng)建學(xué)生表的字段 * @param age * @param gender * @param name * @return */public long createStudent(String age, String gender, String name) {long createResult = 0; ContentValues initialValues = new ContentValues(); initialValues.put(KEY_AGE, age); initialValues.put(KEY_GENDER, gender); initialValues.put(KEY_NAME, name);try { createResult = mDb.insert(SQLITE_TABLE, null, initialValues); } catch (Exception e) {// TODO: handle exception }return createResult; }/** * 刪除表的全部字段數(shù)據(jù) * @return */public boolean deleteAllStudents() {int doneDelete = 0;try { doneDelete = mDb.delete(SQLITE_TABLE, null, null); Log.w(TAG, Integer.toString(doneDelete)); Log.e("doneDelete", doneDelete + ""); } catch (Exception e) {// TODO: handle exception e.printStackTrace(); }return doneDelete > 0; }/** * 根據(jù)名稱刪除表中的數(shù)據(jù) * @param name * @return */public boolean deleteTicketByName(String name) {int isDelete; String[] tName; tName = new String[] { name }; isDelete = mDb.delete(SQLITE_TABLE, KEY_AGE + "=?", tName); Log.e("deleteTicket", "isDelete:" + isDelete + "||" + "ticketID=" + name);return isDelete > 0; }public void insertSomeTickets() { }/** * 獲取表中的所有字段 * @return */public ArrayList<Student> fetchAll() { ArrayList<Student> allTicketsList = new ArrayList<Student>(); Cursor mCursor = null; mCursor = mDb.query(SQLITE_TABLE, new String[] { KEY_ROWID, KEY_AGE, KEY_GENDER, KEY_NAME }, null, null, null, null, null);if (mCursor.moveToFirst()) {do { Student st = new Student(); st.setAge(mCursor.getString(mCursor .getColumnIndexOrThrow(KEY_AGE))); st.setGender(mCursor.getString(mCursor .getColumnIndexOrThrow(KEY_GENDER))); st.setName(mCursor.getString(mCursor .getColumnIndexOrThrow(KEY_NAME))); allTicketsList.add(st); } while (mCursor.moveToNext()); }if (mCursor != null && !mCursor.isClosed()) { mCursor.close(); }return allTicketsList; } }
2,創(chuàng)建教師數(shù)據(jù)表類:
public class TeacherDB {public static final String KEY_ROWID = "_id";public static final String KEY_AGE = "age";public static final String KEY_GENDER = "gender";// 還要保留public static final String KEY_NAME = "name";private static final String TAG = "TeacherDbAdapter";private DatabaseHelper mDbHelper;private SQLiteDatabase mDb;// private static final String DATABASE_NAME = "Fortrun_Ticket11";static final String SQLITE_TABLE = "TeacherTable";private static final int DATABASE_VERSION = 1;private final Context mCtx;private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) {super(context, CommDB.DATABASE_NAME, null, CommDB.DATABASE_VERSION); } @Overridepublic void onCreate(SQLiteDatabase db) {// Log.w(TAG, DATABASE_CREATE);// db.execSQL(DATABASE_CREATE); } @Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE); onCreate(db); } }public TeacherDB(Context ctx) {this.mCtx = ctx; }public TeacherDB open() throws SQLException { mDbHelper = new DatabaseHelper(mCtx); mDb = mDbHelper.getWritableDatabase();return this; }public void close() {if (mDbHelper != null) { mDbHelper.close(); } }public long createTeacher(String age, String gender, String name) {long createResult = 0; ContentValues initialValues = new ContentValues(); initialValues.put(KEY_AGE, age); initialValues.put(KEY_GENDER, gender); initialValues.put(KEY_NAME, name);try { createResult = mDb.insert(SQLITE_TABLE, null, initialValues); } catch (Exception e) {// TODO: handle exception }return createResult; }public boolean deleteAllTeachers() {int doneDelete = 0;try { doneDelete = mDb.delete(SQLITE_TABLE, null, null); Log.w(TAG, Integer.toString(doneDelete)); Log.e("doneDelete", doneDelete + ""); } catch (Exception e) {// TODO: handle exception e.printStackTrace(); }return doneDelete > 0; }public boolean deleteTeacherByName(String name) {int isDelete; String[] tName; tName = new String[] { name }; isDelete = mDb.delete(SQLITE_TABLE, KEY_AGE + "=?", tName); Log.e("deleteTicket", "isDelete:" + isDelete + "||" + "ticketID=" + name);return isDelete > 0; }public void insertSomeTickets() { }// 掃描時進(jìn)行判斷本地數(shù)據(jù)庫是否有此ticketIDpublic ArrayList<Teacher> fetchAll() { ArrayList<Teacher> allTeacherList = new ArrayList<Teacher>(); Cursor mCursor = null; mCursor = mDb.query(SQLITE_TABLE, new String[] { KEY_ROWID, KEY_AGE, KEY_GENDER, KEY_NAME }, null, null, null, null, null);if (mCursor.moveToFirst()) {do { Teacher st = new Teacher(); st.setAge(mCursor.getString(mCursor .getColumnIndexOrThrow(KEY_AGE))); st.setGender(mCursor.getString(mCursor .getColumnIndexOrThrow(KEY_GENDER))); st.setName(mCursor.getString(mCursor .getColumnIndexOrThrow(KEY_NAME))); allTeacherList.add(st); } while (mCursor.moveToNext()); }if (mCursor != null && !mCursor.isClosed()) { mCursor.close(); }return allTeacherList; } }
三,調(diào)用public class ShowActivity extends Activity
{
private StudentDB studentDB;private TeacherDB teacherDB;private List<Student> stList = new ArrayList<Student>();private List<Teacher> trList = new ArrayList<Teacher>(); @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_show); studentDB = new StudentDB(this); studentDB.open(); teacherDB = new TeacherDB(this); teacherDB.open(); studentDB.createStudent("28", "男", "阿武"); studentDB.createStudent("24", "女", "小鈴"); teacherDB.createTeacher("40", "男", "何SIR"); teacherDB.createTeacher("45", "女", "MRS謝"); stList = studentDB.fetchAll(); trList = teacherDB.fetchAll();for (int i = 0; i < stList.size(); i++) { Log.e("stList value", stList.get(i).getName()); }for (int i = 0; i < trList.size(); i++) { Log.e("trList value", trList.get(i).getName()); } }
@Overrideprotected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();if (studentDB != null) { studentDB.close(); }if (teacherDB != null) { teacherDB.close(); } } @Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.show, menu);return true; } }
四,結(jié)果驗證;
10-25 16:50:10.321: E/stList value(3953): 阿武
10-25 16:50:10.321: E/stList value(3953): 小鈴
10-25 16:50:10.321: E/trList value(3953): 何SIR
10-25 16:50:10.321: E/trList value(3953): MRS謝
五,注意事項:
此例子中插入數(shù)據(jù)庫的數(shù)據(jù)是以年齡作為唯一字段,當(dāng)插入的數(shù)據(jù)中,年齡字段有重復(fù)時,數(shù)據(jù)庫會報錯,此例子只為說明如何在一個數(shù)據(jù)庫中建立多張表,因此,在實際項目中,一般以某個實體的ID作為唯一字段,且插入前必須經(jīng)過判斷;
另外,數(shù)據(jù)庫的關(guān)閉,我們選擇在onDestroy()方法中調(diào)用。
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。
網(wǎng)站題目:Android項目中如何在一個數(shù)據(jù)庫里建立多張表
網(wǎng)頁鏈接:http://m.newbst.com/article42/jpjgec.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化、品牌網(wǎng)站制作、定制開發(fā)、微信公眾號、移動網(wǎng)站建設(shè)、全網(wǎng)營銷推廣
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)