First draw a map to understand the next Android database operation of the simple process:
1. First, write a help class for your own database operations, which inherits from the Android Sqliteopenhelper.
2. Some methods of using your own helper to write database operations at your own DAO layer
3.Activity invoke the DAO layer's database action method to operate
The following examples are:
1.Helper
Copy Code code as follows:
Package cn.learn.db.util;
Import Android.content.Context;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.database.sqlite.SQLiteOpenHelper;
Import Android.database.sqlite.SQLiteDatabase.CursorFactory;
public class DBHelper extends Sqliteopenhelper {
Private final static String db_name = "test.db";//Database name
Private final static int version = 1;//version number
The construction method of self-belt
Public DBHelper (context, String name, Cursorfactory factory,
int version) {
Super (context, name, Factory, version);
}
To define a new construction method for each construct without passing in dbname and version numbers
Public DBHelper (context Cxt) {
This (CXT, db_name, NULL, VERSION);//Call the construction method above
}
When version changes
Public DBHelper (Context Cxt,int version) {
This (cxt,db_name,null,version);
}
Called when the database is created
public void OnCreate (Sqlitedatabase db) {
String sql = "CREATE TABLE student (" +
"ID integer primary key autoincrement," +
"Name varchar (20)," +
"Age int");
Db.execsql (SQL);
}
Called when version is updated
public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
String sql = "update student ...";//own update operation
Db.execsql (SQL);
}
}
2. Write DAO layer
Copy Code code as follows:
Package Cn.learn.db.dao;
Import Android.content.Context;
Import Android.database.sqlite.SQLiteDatabase;
Import cn.learn.db.dao.domain.Student;
Import Cn.learn.db.util.DBHelper;
public class Studentdao {
DBHelper helper = null;
Public Studentdao (context Cxt) {
Helper = new DBHelper (CXT);
}
/**
* When this constructor is called in an activity, and a version number is passed in, the system calls the helper's Onupgrade () method to update the next time the database is called
* @param CXT
* @param version
*/
Public Studentdao (context cxt, int version) {
Helper = new DBHelper (CXT, version);
}
Insert operation
public void InsertData (Student stu) {
String sql = "INSERT into student (Name,age) VALUES (?,?)";
Sqlitedatabase db = Helper.getwritabledatabase ();
Db.execsql (SQL, new object[] {stu.name, stu.age});
}
Other actions
}
To do this, the other operation is simple ....
In addition, the database files are placed in this directory