Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create multiple tables in one database in an Android project

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

Android project how to build multiple tables in a database, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.

First, create a public DBAdapter

In order to call the public database during the entire program run, we define a CommDB class that extends from Application:

1, create a unique database:

1 public class CommDB {2 3 public static final String DATABASE_NAME = "myDatabase"; / / Database name 4 5 public static final int DATABASE_VERSION = 1 6 / / statement 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 + ")) " / / temporarily stipulate that you cannot rename 14 / / create the statement 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 + ") of the teacher table under the database. "+ 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); / / create student form 46 db.execSQL (CREATE_TABLE_Teachers) / / create teacher's form 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. When app starts to run, create the above database and the corresponding data table:

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}

Second, create corresponding data tables

1. Set up the class of student data table:

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 () }} / * create fields * @ 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;} / * Delete all field data of the table * @ return * / public boolean deleteAllStudents () {int doneDelete = 0try {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;} / * delete the data in the table according to the name * @ 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 () {} / * * get all fields in the table * @ return * / public ArrayList fetchAll () {ArrayList allTicketsList = new ArrayList () Cursor mCursor = null; mCursor = mDb.query (SQLITE_TABLE, new String [] {KEY_ROWID, KEY_AGE, KEY_GENDER, KEY_NAME}, 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. Create the teacher data table class:

Public class TeacherDB {public static final String KEY_ROWID = "_ id"; public static final String KEY_AGE = "age"; public static final String KEY_GENDER = "gender"; / / also keep 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 = 1private 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 = 0tre {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 () {} / / scan to determine whether the local database has this ticketIDpublic ArrayList fetchAll () {ArrayList allTeacherList = new ArrayList () Cursor mCursor = null; mCursor = mDb.query (SQLITE_TABLE, new String [] {KEY_ROWID, KEY_AGE, KEY_GENDER, KEY_NAME}, 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;}}

Third, call public class ShowActivity extends Activity

{

Private StudentDB studentDB;private TeacherDB teacherDB;private List stList = new ArrayList (); private List trList = new ArrayList (); @ 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", "male", "Ah Wu"); studentDB.createStudent ("24", "female", "Xiaoling"); teacherDB.createTeacher ("40", "male", "he SIR"); teacherDB.createTeacher ("45", "female", "MRS Xie"); stList = studentDB.fetchAll (); trList = teacherDB.fetchAll () For (int I = 0; I < stList.size (); getName +) {Log.e ("stList value", stList.get (I). GetName ());} for (int I = 0; I < trList.size (); iTunes +) {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;}}

Fourth, the result is verified.

10-25 16-50 10.321: E/stList value (3953): Ah Wu

10-25 16-50 10.321: E/stList value (3953): small bell

10-25 16-50 10.321: E/trList value (3953): he SIR

10-25 16-50 10.321: E/trList value (3953): MRS Xie

Fifth, points for attention:

In this example, the data inserted into the database takes age as the only field. When there are duplicates in the inserted data, the database will report an error. This example is only to illustrate how to create multiple tables in a database. Therefore, in the actual project, the ID of an entity is generally taken as the only field, and must be judged before insertion.

In addition, for the shutdown of the database, we choose to call it in the onDestroy () method.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report