Android中数据库的常用操作

制作一个APP模拟电子书店的一部分功能。首先需要创建一个名为BookStore.db的数据库,在数据库中新建一张Book表,表中有id(主键)、作者、价格、页数和书名等列。然后增加一些按钮,分别实现对该数据库进行增加或删除书籍,修改价格,查找书籍信息等操作的功能

在activity_main.xml文件中创建布局,代码如下:

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:id="@+id/activity_main"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     android:paddingBottom="@dimen/activity_vertical_margin"  
  8.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  9.     android:paddingRight="@dimen/activity_horizontal_margin"  
  10.     android:paddingTop="@dimen/activity_vertical_margin"  
  11.     android:orientation="vertical"  
  12.     tools:context="bzu.edu.cn.databasedemo.MainActivity">  
  13.   
  14.     <Button  
  15.         android:layout_width="match_parent"  
  16.         android:layout_height="wrap_content"  
  17.         android:text="CreateDatabase"  
  18.         android:onClick="createDatabase"  
  19.         android:id="@+id/btnCreateDB"/>  
  20.     <Button  
  21.         android:layout_width="match_parent"  
  22.         android:layout_height="wrap_content"  
  23.         android:text="AddDatabase"  
  24.         android:onClick="addDatabase"  
  25.         android:layout_marginTop="10dp"  
  26.         android:id="@+id/btnAddDB"/>  
  27.     <Button  
  28.     android:layout_width="match_parent"  
  29.     android:layout_height="wrap_content"  
  30.     android:text="UpdateDatabase"  
  31.     android:onClick="updateDatabase"  
  32.     android:layout_marginTop="10dp"  
  33.     android:id="@+id/btnUpdateDB"/>  
  34.     <Button  
  35.         android:layout_width="match_parent"  
  36.         android:layout_height="wrap_content"  
  37.         android:text="DeleteDatabase"  
  38.         android:onClick="deleteDatabase"  
  39.         android:layout_marginTop="10dp"  
  40.         android:id="@+id/btnDeleteDB"/>  
  41.     <Button  
  42.         android:layout_width="match_parent"  
  43.         android:layout_height="wrap_content"  
  44.         android:text="QueryDatabase"  
  45.         android:onClick="queryDatabase"  
  46.         android:layout_marginTop="10dp"  
  47.         android:id="@+id/btnQueryDB"/>  
  48. </LinearLayout>  
布局如下图所示:

Android中数据库的常用操作

新建一个辅助类DBHelper,代码如下:

Android系统推荐使用SQLiteOpenHelper的子类创建SQLite数据库,因此需要创建一个类继承自

SQLiteOpenHelper,重写onCreate()方法,并在该方法中执行创建数据库的命令。创建数据库的SQL

语句被定义在onCreate()方法中,当数据库第一次被创建时会自动调用该方法中的SQL语句。当数据库

版本号增加时会调用onUpgrade()方法,如果版本号不增加,该方法则不会被调用。

[html] view plain copy
  1. package bzu.edu.cn.databasedemo.db;  
  2.   
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteOpenHelper;  
  6. import android.util.Log;  
  7. import android.widget.Toast;  
  8.   
  9. /**  
  10.  * Created by Administrator on 2017/4/12.  
  11.  */  
  12.   
  13. public class DBHelper extends SQLiteOpenHelper {  
  14.     private Context context;  
  15.     public static final String DB_NAME="BookStore.db";  
  16.     public static final String CREATE_BOOK="create table book(id integer primary key autoincrement,author text,price real,pages integer,name text)";  
  17.     public static final String CREATE_CATEGORY="create table category(id integer primary key autoincrement,name text,code integer)";  
  18.     public DBHelper(Context context, int version) {  
  19.         super(context, DB_NAME, null, version);  
  20.         Log.d("DBHelper","constructor");  
  21.         this.context=context;  
  22.     }  
  23.   
  24.     @Override  
  25.     public void onCreate(SQLiteDatabase db) {  
  26.         Log.d("DBHelper","onCreate");  
  27.         db.execSQL(CREATE_BOOK);  
  28.         db.execSQL(CREATE_CATEGORY);  
  29.         Toast.makeText(context,"create succeeded",Toast.LENGTH_LONG).show();  
  30.     }  
  31.   
  32.     @Override  
  33.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//数据库的升级  
  34.         db.execSQL("drop table if exists book");  
  35.         db.execSQL("drop table if exists category");  
  36.         onCreate(db);  
  37.   
  38.     }  
  39. }  
在MainActivity中写对数据库操作的各种方法,代码如下:

[html] view plain copy
  1. package bzu.edu.cn.databasedemo;  
  2.   
  3. import android.content.ContentValues;  
  4. import android.database.Cursor;  
  5. import android.database.sqlite.SQLiteDatabase;  
  6. import android.support.v7.app.AppCompatActivity;  
  7. import android.os.Bundle;  
  8. import android.view.View;  
  9. import android.widget.Toast;  
  10.   
  11. import bzu.edu.cn.databasedemo.db.DBHelper;  
  12.   
  13. public class MainActivity extends AppCompatActivity {  
  14.     private DBHelper dbHelper;  
  15.   
  16.     @Override  
  17.     protected void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.activity_main);  
  20.         dbHelper = new DBHelper(this, 2);  
  21.     }  
  22.   
  23.     public void createDatabase(View v) {//创建建数据库  
  24.         dbHelper.getWritableDatabase();  
  25.     }  
  26.   
  27.     public void addDatabase(View v) {//添加数据  
  28.         SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();  
  29.         ContentValues contentValues = new ContentValues();  
  30.         contentValues.put("name", "Java");  
  31.         contentValues.put("author", "孙卫青");  
  32.         contentValues.put("pages", 500);  
  33.         contentValues.put("price", 56.5);  
  34.         sqLiteDatabase.insert("book", null, contentValues);  
  35.         contentValues.clear();  
  36.         contentValues.put("name", "C++");  
  37.         contentValues.put("author", "Dan");  
  38.         contentValues.put("pages", 400);  
  39.         contentValues.put("price", 56);  
  40.         sqLiteDatabase.insert("book", null, contentValues);  
  41.     }  
  42.   
  43.     public void updateDatabase(View v) {//更新数据  
  44.         SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();  
  45.         ContentValues contentValues = new ContentValues();  
  46.         contentValues.put("price", 10.8);  
  47.         sqLiteDatabase.update("book", contentValues, "name=?", new String[]{"Java"});  
  48.     }  
  49.   
  50.     public void deleteDatabase(View v) {//删除数据  
  51.         SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();  
  52.         sqLiteDatabase.delete("book", "pages<?", new String[]{"500"});  
  53.     }  
  54.   
  55.     public void queryDatabase(View v) {//查询数据  
  56.         StringBuilder stringBuilder = new StringBuilder();  
  57.         SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();  
  58.         Cursor cursor = sqLiteDatabase.query("book", null, null, null, null, null, null);  
  59.         if (cursor.moveToFirst()) {  
  60.             do {  
  61.                 //遍历Cursor对象,取出数据并打印  
  62.                 String name = cursor.getString(cursor.getColumnIndex("name"));  
  63.                 String author = cursor.getString(cursor.getColumnIndex("author"));  
  64.                 int pages = cursor.getInt(cursor.getColumnIndex("pages"));  
  65.                 double price = cursor.getDouble(cursor.getColumnIndex("price"));  
  66.                 stringBuilder.append(name + "-" + author + "-" + pages + "-" + price+"\n");  
  67.             } while (cursor.moveToNext());  
  68.         }  
  69.         Toast.makeText(this, stringBuilder.toString(),Toast.LENGTH_LONG).show();  
  70.     }  
  71. }