Android中的数据库采用的是SQLite,这是一款轻型数据库,占用资源虽小但是功能强大,能满足系统中的各种数据操作。它不仅可以支持通过SQL语句操作,同时也可以通过SQLiteDatabase对象中的各种方法来操作数据库。
在数据库编程中,常常使用一个继承自SQLiteOpenHelper类的数据库操作类,在这个类封装了一些关于数据库生命周期的方法,可以更加方便的使用数据库。代码如下:
- public class myDatabase {
-
- static final String USERID="_id";
- static final String PASSWORD="password";
- static final String EMAIL="email";
- static final String QQ="qq";
- static final String CAREER="career";
- static final String DB_NAME="myDatabase1";
- static final String DB_TABLE="imfor";
- private static final int VERSION=1;
- private Context mContext;
- SQLiteDatabase mySQLite;
-
- private static String DB_CREATE="CREATE TABLE " +DB_TABLE+" (" +USERID+" INTEGER PRIMARY KEY,"
- +PASSWORD+" TEXT,"
- +EMAIL+" TEXT,"
- +QQ+" TEXT,"
- +CAREER+" TEXT)";
-
-
- private static class MyHelper extends SQLiteOpenHelper{
-
- public MyHelper(Context context) {
- super(context, DB_NAME, null, VERSION);
-
- }
-
- @Override
- public void onCreate(SQLiteDatabase db) {
-
- db.execSQL(DB_CREATE);
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
-
-
- }
-
- }
-
-
- public myDatabase(Context context){
- mContext=context;
- }
-
- public void openDatabase(){
- MyHelper myhelper=new MyHelper(mContext);
- //这时创建或打开数据库,如果数据库是新创建的则激活SQLiteOpenHelper对象的的onCreate()方法
- mySQLite=myhelper.getWritableDatabase();
- }
-
- public long insert(int id,String password,String email,String qq,String career){
- ContentValues cv=new ContentValues();
- cv.put(USERID, id);
- cv.put(PASSWORD, password);
- cv.put(EMAIL, email);
- cv.put(QQ, qq);
- cv.put(CAREER, career);
- return mySQLite.insert(DB_TABLE, "null",cv);
- }
-
- public Cursor fetchData(int id){
-
- return mySQLite.query(DB_TABLE, new String[] {USERID,PASSWORD,EMAIL,QQ,CAREER}, USERID+"="+id, null, null, null, null);
- }
- }
|
在上面的这个myDataBase类中定义了继承于SQLiteOpenHelper类的内部类,用于创建数据库相关操作。另外又定义了两个数据库的操作方法,插入数据和查询数据。关于这些基本的数据库操作一方面可以直接调用数据库对象的execSQL(String)方法,将SQL语句作为参数。另外数据库对象中又定义了一些方法,通过SDK文档可以方便的查询以便使用。
转载于:https://blog.51cto.com/52android/478368