Android中数据库的常用操作
制作一个APP模拟电子书店的一部分功能。首先需要创建一个名为BookStore.db的数据库,在数据库中新建一张Book表,表中有id(主键)、作者、价格、页数和书名等列。然后增加一些按钮,分别实现对该数据库进行增加或删除书籍,修改价格,查找书籍信息等操作的功能
在activity_main.xml文件中创建布局,代码如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/activity_main"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- android:orientation="vertical"
- tools:context="bzu.edu.cn.databasedemo.MainActivity">
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="CreateDatabase"
- android:onClick="createDatabase"
- android:id="@+id/btnCreateDB"/>
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="AddDatabase"
- android:onClick="addDatabase"
- android:layout_marginTop="10dp"
- android:id="@+id/btnAddDB"/>
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="UpdateDatabase"
- android:onClick="updateDatabase"
- android:layout_marginTop="10dp"
- android:id="@+id/btnUpdateDB"/>
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="DeleteDatabase"
- android:onClick="deleteDatabase"
- android:layout_marginTop="10dp"
- android:id="@+id/btnDeleteDB"/>
- <Button
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="QueryDatabase"
- android:onClick="queryDatabase"
- android:layout_marginTop="10dp"
- android:id="@+id/btnQueryDB"/>
- </LinearLayout>
新建一个辅助类DBHelper,代码如下:
Android系统推荐使用SQLiteOpenHelper的子类创建SQLite数据库,因此需要创建一个类继承自
SQLiteOpenHelper,重写onCreate()方法,并在该方法中执行创建数据库的命令。创建数据库的SQL
语句被定义在onCreate()方法中,当数据库第一次被创建时会自动调用该方法中的SQL语句。当数据库
版本号增加时会调用onUpgrade()方法,如果版本号不增加,该方法则不会被调用。
- package bzu.edu.cn.databasedemo.db;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- import android.util.Log;
- import android.widget.Toast;
- /**
- * Created by Administrator on 2017/4/12.
- */
- public class DBHelper extends SQLiteOpenHelper {
- private Context context;
- public static final String DB_NAME="BookStore.db";
- public static final String CREATE_BOOK="create table book(id integer primary key autoincrement,author text,price real,pages integer,name text)";
- public static final String CREATE_CATEGORY="create table category(id integer primary key autoincrement,name text,code integer)";
- public DBHelper(Context context, int version) {
- super(context, DB_NAME, null, version);
- Log.d("DBHelper","constructor");
- this.context=context;
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- Log.d("DBHelper","onCreate");
- db.execSQL(CREATE_BOOK);
- db.execSQL(CREATE_CATEGORY);
- Toast.makeText(context,"create succeeded",Toast.LENGTH_LONG).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);
- }
- }
- package bzu.edu.cn.databasedemo;
- import android.content.ContentValues;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Toast;
- import bzu.edu.cn.databasedemo.db.DBHelper;
- public class MainActivity extends AppCompatActivity {
- private DBHelper dbHelper;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- dbHelper = new DBHelper(this, 2);
- }
- public void createDatabase(View v) {//创建建数据库
- dbHelper.getWritableDatabase();
- }
- public void addDatabase(View v) {//添加数据
- SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();
- ContentValues contentValues = new ContentValues();
- contentValues.put("name", "Java");
- contentValues.put("author", "孙卫青");
- contentValues.put("pages", 500);
- contentValues.put("price", 56.5);
- sqLiteDatabase.insert("book", null, contentValues);
- contentValues.clear();
- contentValues.put("name", "C++");
- contentValues.put("author", "Dan");
- contentValues.put("pages", 400);
- contentValues.put("price", 56);
- sqLiteDatabase.insert("book", null, contentValues);
- }
- public void updateDatabase(View v) {//更新数据
- SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();
- ContentValues contentValues = new ContentValues();
- contentValues.put("price", 10.8);
- sqLiteDatabase.update("book", contentValues, "name=?", new String[]{"Java"});
- }
- public void deleteDatabase(View v) {//删除数据
- SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();
- sqLiteDatabase.delete("book", "pages<?", new String[]{"500"});
- }
- public void queryDatabase(View v) {//查询数据
- StringBuilder stringBuilder = new StringBuilder();
- SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();
- Cursor cursor = sqLiteDatabase.query("book", null, null, null, null, null, null);
- if (cursor.moveToFirst()) {
- do {
- //遍历Cursor对象,取出数据并打印
- String name = cursor.getString(cursor.getColumnIndex("name"));
- String author = cursor.getString(cursor.getColumnIndex("author"));
- int pages = cursor.getInt(cursor.getColumnIndex("pages"));
- double price = cursor.getDouble(cursor.getColumnIndex("price"));
- stringBuilder.append(name + "-" + author + "-" + pages + "-" + price+"\n");
- } while (cursor.moveToNext());
- }
- Toast.makeText(this, stringBuilder.toString(),Toast.LENGTH_LONG).show();
- }
- }