【Android基础知识】Sqlite数据库的详细使用

当前位置: 首页 >  移动开发 >  Android开发 > 正文

【Android基础知识】Sqlite数据库的详细使用

发布时间: 2016-08-03   作者:本站编辑   浏览次数: 3 
摘要: Android使用SQLiteOpenHelper 类来辅助使用数据库,这里我们来详细介绍数据库的crud操作、事务操作、数据库升级的相关知识。 S...

Android使用SQLiteOpenHelper 类来辅助使用数据库,这里我们来详细介绍数据库的crud操作、事务操作、数据库升级的相关知识。

SQLiteOpenHelper 类

public class MyDatabaseHelper extends SQLiteOpenHelper{

	public static final String CREATE_TABLE = "create table book("
			+ "id integer primary key autoincrement, "
			+ "author text, "
			+ "price real, "
			+ "pages integer, "
			+ "name text,"
			+ "category_id integer)";
	//升级数据库,我们加入了一张新的表
	public static final String CREATE_CATEGORY = "create table Category("
			+ "id integer primary key autoincrement, "
			+ "category_name text, "
			+ "category_code integer)";
	
	private Context mContext;
	public MyDatabaseHelper(Context context, String name,
			CursorFactory factory, int version) {
		super(context, name, factory, version);
		mContext = context;
	}
	//onCreate 方法会在调用getReadableDatabase或者WriteableDatabase时并且数据库不存在时才会被调用,数据库如果
	//已经存在则不会调用。
	@Override
	public void onCreate(SQLiteDatabase db) {
		//创建表
		db.execSQL(CREATE_TABLE);
		db.execSQL(CREATE_CATEGORY);
		Toast.makeText(mContext, "create table successful", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		/*方法1:升级数据库最粗暴的方法,由于数据库已经存在时,不会调用onCreate方法,
		 * 所以删除表,重新调用onCreate方法,不可取
		 */
//		db.execSQL("drop table if exists Book");
//		db.execSQL("drop table if exists Category");
//		onCreate(db);
		/*
		 * 方法2:升级数据库的最佳实践,每一个数据库版本都会对应一个版本号,当指定的数据库版本号大于当前的版本
		 * 号的时候,就会进入到onUpgrade()方法中去执行更新操作。这里需要为每一个版本号赋予它各自改变的内容,然后在
		 * onUpgrade 方法中执行更新操作
		 * 这里来模拟一个数据库升级的案例
		 * 第1版本就一个book表
		 * 第二版本需要新加一个Category表
		 * 
		 */
		//注意一个细节,这里我们没有写break,为了跨版本升级时都可以执行到
		Toast.makeText(mContext, "oldVersion",Toast.LENGTH_LONG).show();
		switch (oldVersion) {
		case 1:
			db.execSQL(CREATE_CATEGORY);
		case 2:
			db.execSQL("alter table book add column category_id integer");
		default:
		}
	}

}
上面这个类为SQLiteOpenHelper类 ,注意其中onCreate 方法的调用时机,它在我们调用  getReadableDatabase 或者getWriteableDatabase 并且数据库不存在时会调用一次,如果数据库的版本变化则会去调用onUpgrade方法去更新数据库。

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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" >

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

    <Button
        android:id="@+id/add_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add Data" />

    <Button
        android:id="@+id/update_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Update data" />

    <Button
        android:id="@+id/delete_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Delete data" />

    <Button
        android:id="@+id/query_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Query Data" />

    <Button
        android:id="@+id/replace_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Replace data" />

</LinearLayout>

一个LinearLayout  ,包括创建数据库、增删改查,事务操作等按钮。

MainActivity.java

package com.example.sqllearn;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends Activity {
	private Button createDatabase;
	private Button addData;
	private Button updateData;
	private Button deleteButton;
	private Button queryButton;
	private Button replaceButton;
	MyDatabaseHelper helper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //helper = new MyDatabaseHelper(this, "BookStore.db", null, 1);
        //把版本号改为2 进行数据库的升级
//        helper = new MyDatabaseHelper(this, "BookStore.db", null, 2);
        helper = new MyDatabaseHelper(this, "BookStore.db", null, 5);
        createDatabase = (Button)findViewById(R.id.create_database);
        createDatabase.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//调用这一句还没有数据库时会调用oncreate方法,否则根据版本信息会调用
				//ononUpgrade 方法
				helper.getReadableDatabase();
			}
		});
        addData = (Button)findViewById(R.id.add_data);
        addData.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//添加数据
				SQLiteDatabase db = helper.getWritableDatabase();
				ContentValues values = new ContentValues();
				values.put("name", "The Da Vinci Code");
				values.put("author", "Dan Brown");
				values.put("pages", 454);
				values.put("price", 16.96);
				//插入第一条数据
				db.insert("Book", null, values);
				values.clear();
				//开始组装第二条数据
				values.put("name", "The Lost Symbol");
				values.put("author", "Dan Brown");
				values.put("pages", 510);
				values.put("price", 19.95);
				db.insert("Book", null, values); //  插入第二条数据
			}
		});
        updateData = (Button)findViewById(R.id.update_data);
        updateData.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				SQLiteDatabase db = helper.getWritableDatabase();
				ContentValues values = new ContentValues();
				values.put("price", 10.99);
				db.update("Book", values,"name=?",new String[]{"The Da Vinci Code"});
			}
		});
        deleteButton = (Button)findViewById(R.id.delete_data);
        deleteButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				SQLiteDatabase db = helper.getWritableDatabase();
				//删除页数大于500的书
				db.delete("Book","pages>?", new String[]{"500"});
			}
		});
        queryButton = (Button)findViewById(R.id.query_data);
        queryButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				SQLiteDatabase db = helper.getReadableDatabase();
				Cursor cursor = db.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"));
						Toast.makeText(
								MainActivity.this,
								name + "--" + author + "--" + pages + "--"
										+ price, Toast.LENGTH_SHORT).show();
					}while(cursor.moveToNext());
				}
				cursor.close();
			}
		});
        replaceButton = (Button)findViewById(R.id.replace_data);
        replaceButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				SQLiteDatabase db = helper.getWritableDatabase();
				db.beginTransaction();//开启事务
				try{
					db.delete("Book",null, null);
					if(true){
						//手动抛出一个异常,让事务失败,注释掉这一句则事务执行成功
//						throw new NullPointerException();
					}
					ContentValues values = new ContentValues();
					values.put("name", "Game of Thrones");
					values.put("author", "George Martin");
					values.put("pages", 720);
					values.put("price", 20.85);
					db.insert("Book", null, values);
					db.setTransactionSuccessful(); //事务执行成功
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					db.endTransaction();//结束事务
				}
			}
		});
        /*
         * 使用 Sql 语句操作数据库
         * 
         * 
         */
		/*SQLiteDatabase db = openOrCreateDatabase("BookStore.db", MODE_PRIVATE,
				null);
		db.execSQL(
				"insert into Book (name, author, pages, price) values(?, ?, ?, ?)",
				new String[] { "The Da Vinci Code", "Dan Brown", "454", "16.96" });
		db.execSQL(
				"insert into Book (name, author, pages, price) values(?, ?, ?, ?)",
				new String[] { "The Lost Symbol", "Dan Brown", "510", "19.95" });
		db.execSQL("update Book set price = ? where name = ?", new String[] {
				"10.99", "The Da Vinci Code" });
		db.execSQL("delete from Book where pages > ?", new String[] { "500" });
		db.rawQuery("select * from Book", null);*/
        		
        		
    }
}
这里对代码做简单记录,详细过程请去看《第一行代码》这本书,推荐下。 






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值