Inventory before the Android final exam (seven): SQLite (on)

SQLite is also a very important test point, but why put it at the end, the fact is that it is more difficult, and it is generally combined with login registration and ListView.

SQLite can simply be understood as MySql or SQLserver stored in the mobile phone.

In Android studio, using SQLite must involve two classes SQLiteDatabase , SQLiteOpenHelper

Simply put:

SQLiteOpenHelper: used to create databases and tables

SQLiteDatabase: used to operate the database, that is, adding, deleting, modifying and checking

The steps to use SQLite, think in your head when using:

  1. Write a database class to create databases and tables, inherit from SQLiteOpenHelper, and rewrite the method. The shortcut key for quick rewriting is Alt+Enter, and select rewriting
  2. The following three methods are rewritten in the database class: construction method, onCreate method, onUpgrade method, super keyword is used in the construction method, and parameters are passed: context, database file name, factory (ignore it, fill in null), version (ignore It, just fill in 1); in the onCreate method, execute the execSQL method of SQLiteDatabase to create a data table; in the onUpgrade method, ignore it and leave it empty.
 public  class MyHelper extends SQLiteOpenHelper {
        public MyHelper(Context context){
               //上下文、数据库文件名   后面两个参数工厂与版本别管
            super(context,"user.db",null,1);
        }
        @Override
        public void onCreate(SQLiteDatabase db) {
        //创建表SQL语句  需要一些SQL语句基础
        //以下SQL语句就是 创建user表,第一个字段为id为自增 int型,第二个字段为account 类型为//varchar,可以理解为字符串型,第三个也是字符串型的password
            db.execSQL("CREATE TABLE user(id INTEGER PRIMARY KEY AUTO" +
                    "INCREMENT ,account VARCHAR(20),password VARCHAR(20))");

        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }

    }

3. Where data operations are required, the data class above new uses the SQLiteDatabase object to perform additions, deletions, modifications, and queries, such as the following registration button click operation event

MyHelper myHelper;
SQLiteDatabase db;
ContentValues values;
myHelper=new MyHelper(this);//new实例化对象
db=myHelper.getWritableDatabase();//获取可读写SQLiteDarabse对象
values=new ContentValues();//创建ContentValues对象 一般用于数据库插入用
values.put("account",account);//设置账号数据
values.put("password",password);//设置密码数据
db.insert("user",null,values);//向user表添加数据    insert方法
db.close();//关闭

おすすめ

転載: blog.csdn.net/m0_59558544/article/details/131335004