Android built-in database SQLite

Android provides a class SQLiteOpenHelper help us to help us to easily manage the database. But SQLiteOpenHelper is an abstract class, we need to create a class of their own to inherit it and override its onCreate (), onUpgrade () method, in which these two methods to write to create, upgrade logical database.

getReadableDatabase (), getwriteableDatabase () can create or open an existing database (if the database already exists directly open, or on their own to create a database), however, when the database can not write, getReadableDatabase () method can only open the database in read-only mode, and getwriteableDatabase () method errors will occur.

public class MyDatabaseHelper extends SQLiteOpenHelper {
    public static final String CREAT_BOOK="creat table book ("
            +"id integer primary key autoincrement,"
            +"author text,"
            +"price real,"
            +"pages integer,"
            +"name text)";
    private Context mContext;
    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        this.mContext = mContext;
    }
    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL(CREAT_BOOK);
        Toast.makeText(mContext,"Create suceeded",Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){

    }
}

Here, I created a class that inherits MyDatabaseHelper SQLiteOpenHelper abstract class and overrides a constructor. Here, I simply say that the various parameters inside the constructor: the first is Context, the second is the name of the database, it is the third parameter allows us to return when querying data a Cursor, general pass null, the fourth parameter It indicates the version number of the database; here we also build table statement is defined as a string constant; then we call execSQL () method onCreate () method to go inside the implementation of this statement is to build the table, pop up a Toast.

Paste the XML code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/create_database"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Create database"/>
  </LinearLayout>

Paste code MainActivity

public class MainActivity extends AppCompatActivity {
    private MyDatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbHelper=new MyDatabaseHelper(getApplicationContext(),"BookStore",null,1);
        Button createDatabase=(Button)findViewById(R.id.create_database);
        createDatabase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dbHelper.getReadableDatabase();
            }
        });
      }
}

After this operation, the database will establish a success.

Upgrading the database

In the above, we do not rewrite onUpgrade () method in MyDatabaseHelper, this method is used to upgrade the database.

Next, we need to add a table inside the database, which added MyDatabaseHelper

public static final String CREATE_CATEGORY="create table Category("
            +"id integer primary key autoincrement,"
            +"category_name text,"
            +"category_code integer)";
@Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL(CREAT_BOOK);
        db.execSQL(CREATE_CATEGORY);

       Toast.makeText(mContext,"Create suceeded",Toast.LENGTH_SHORT).show();
    }

But after the example above, if we have run before, so this time we may find that we once again run the results will not be as we want it, what causes it? The reason is that the database already exists at this time (the first time we run database created). So we click Button button, MyDatabaseHelper inside onCreate () method will no longer be executed. This time we need to run the function SQLiteOpenHelper upgrade. Modify the code as follows

@Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL(CREAT_BOOK);
        db.execSQL(CREATE_CATEGORY);

        Toast.makeText(mContext,"Create suceeded",Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
        db.execSQL("drop table if exists Book");
        db.execSQL("drop table if exists Category");
        onCreate(db);
    }

I performed onUpgrade () method in the two DROP statements, if it is found inside the database already exists Book table or Category table, then put it to delete, and then perform the onCreate () method.

How to make onUpgrade () method performs, and here we only need MainActivity inside the last parameter MyDatabaseHelper () constructor inside pass a large number of figures than the original version on it.

Published 37 original articles · won praise 10 · views 10000 +

Guess you like

Origin blog.csdn.net/OneLinee/article/details/78639135
Recommended