一天一点Android知识(SQLite数据库存储)

借助SQLiteOpenHelper帮助类实现对数据库的创建和升级。
MainActivity.java

package com.example.databasetest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

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(this,"BookStore.db",null,1);
        Button createDatabase =(Button)findViewById(R.id.create_database);
        createDatabase.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                dbHelper.getWritableDatabase();
            }
        });

    }
}

MyDatabaseHelper.java

package com.example.databasetest;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

/**
 * Created by Codingbo on 2017/1/19.
 */

public class MyDatabaseHelper extends SQLiteOpenHelper {
    public  static final String CREATE_BOOK = "create table Book( " +
            "id integer primary key autoincrement,"
    +"author text,"+"preice real,"+"pages integer,"+"name text)";

    private Context mContext;
    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
                            int version){
        super(context,name,factory,version);
        mContext=context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
        Toast.makeText(mContext,"Create succeed",Toast.LENGTH_SHORT).show();
    }

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

    }
}

activity_main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

一天一点Android知识(SQLite数据库存储)_第1张图片

你可能感兴趣的:(Android移动开发)