• SQLiteOpenHelper的使用


     1 import android.content.Context;
     2 import android.database.SQLException;
     3 import android.database.sqlite.SQLiteDatabase;
     4 import android.database.sqlite.SQLiteOpenHelper;
     5 
     6 public class NoteDBHelper extends SQLiteOpenHelper {
     7 
     8     private static final String DATABASE_NAME = "notedatabase.db";
     9     private static final String TABLE_NAME = "NOTETABLE";
    10     private static final String UID = "_id";
    11     private static final String NAME = "Name";
    12     private static final int DATABASE_VERSION = 1;//upgrade时需要改版本号
    13     private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME
    14             +"("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255))";
    15     private static final String DROP_TABLE = "DROP TABLE IF EXISTS"+TABLE_NAME;
    16     private Context context;  
    17 
    18     NoteDBHelper(Context context){
    19 
    20         super(context, DATABASE_NAME, null, DATABASE_VERSION);
    21         this.context=context;
    22         Message.message(context, "constructor called");
    23     }
    24 
    25     public void onCreate(SQLiteDatabase db){
    26 
    27         try {
    28             db.execSQL(CREATE_TABLE);
    29             Message.message(context, "onCreate called");
    30         }catch (SQLException e){
    31 
    32             Message.message(context, ""+e);
    33         }
    34 
    35     }
    36 
    37     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
    38 
    39         try {
    40             db.execSQL(DROP_TABLE);
    41             onCreate(db);
    42             Message.message(context, "onUpgrade called");
    43         }catch (SQLException e){
    44 
    45             Message.message(context, "" + e);
    46         }
    47 
    48     }
    49 }

    在Activity中:

     1 NoteDBHelper noteDBHelper;
     2 
     3 @Override
     4     protected void onCreate(Bundle savedInstanceState) {
     5 
     6         super.onCreate(savedInstanceState);
     7         setContentView(R.layout.activity_activity_demo);
     8 
     9         noteDBHelper = new NoteDBHelper(this);//have not yet accessed the database
    10         SQLiteDatabase sqLiteDatabase = noteDBHelper.getWritableDatabase();//this time noteDBhelper call onCreate()
    11         Log.e(TAG, "start onCreate()~~~~~");
    12     }

    这样在第一次运行app的时候一个叫notedatabase.db的数据库文件将会在android设备的/data/data/com.practice.apple.activitydemo/目录下生成,可以拷到电脑上进行操作。

    (/data/data正常情况下是没有读写权限的,可以机器先root然后把这个目录的权限改成可读写,比如RE)

  • 相关阅读:
    创建对象的七种方式
    设计模式之工厂模式
    设计模式之单例模式
    排序算法之插入排序
    排序算法之选择排序
    类及对象初体验
    排序算法之冒泡排序
    迭代器和生成器
    装饰器
    函数进阶
  • 原文地址:https://www.cnblogs.com/turtle920/p/4859304.html
Copyright © 2020-2023  润新知