天天看點

Android自學之sqlite資料的基本操作和事物的簡單應用

  SQLite 是一款輕量級的關系型資料庫, 它的運算速度非常快,占用資源很少, 通常隻需要幾百 K的記憶體就足夠了, 因而特别适合在移動裝置上使用。 SQLite不僅支援标準的 SQL 文法,還遵循了資料庫的 ACID 事務,是以隻要你以前使用過其他的關系型資料庫,就可以很快地上手 SQLite。而 SQLite 又比一般的資料庫要簡單得多,它甚至不用設定使用者名和密碼就可以使用。Android正是把這個功能極為強大的資料庫嵌入到了系統當中,使得本地持久化的功能有了一次質的飛躍。

前面一篇關于SharedPreferences存儲畢竟隻适用于去儲存一些簡單的資料和鍵值對,當需要存儲大量複雜的關系型資料的時候,你就會發現以上兩種存儲方式很難應付得了。比如我們手機的短信程式中可能會有很多個會話,每個會話中又包含了很多條資訊内容,并且大部分會話還可能各自對應了電話簿中的某個聯系人。很難想象如何用檔案或者SharedPreferences來存儲這些資料量大、結構性複雜的資料吧?但是使用資料庫就可以做得到。

具體流程就貼代碼吧

xml代碼:

<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:orientation="vertical"  >

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

   <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>




           

java代碼:

MyDatabaseHelper.java

package com.example.databasetest;

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

public class MyDatabaseHelper extends SQLiteOpenHelper {

	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, "
			+ "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;
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL(CREATE_BOOK);
		db.execSQL(CREATE_CATEGORY);
		Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
	}

	//用于對資料庫更新  插入新表,如果資料庫本身已存在,則調用次函數,删除兩張表,然後重新調用onCreate
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
//		db.execSQL("drop table if exists Book");
//		db.execSQL("drop table if exists Category");
//		onCreate(db);
		
		switch (oldVersion) {
		case 1:
			db.execSQL(CREATE_CATEGORY);
		case 2:
			db.execSQL("alter table Book add column category_id integer");
		default:
		}
		
//		這裡請注意一個非常重要的細節,switch 中每一個 case的最後都是沒有使用 break的,
//		為什麼要這麼做呢?這是為了保證在跨版本更新的時候, 每一次的資料庫修改都能被全部執
//		行到。比如使用者目前是從第二版程式更新到第三版程式的,那麼 case 2中的邏輯就會執行。
//		而如果使用者是直接從第一版程式更新到第三版程式的,那麼 case 1和 case 2中的邏輯都會執
//		行。使用這種方式來維護資料庫的更新,不管版本怎樣更新,都可以保證資料庫的表結構是
//		最新的,而且表中的資料也完全不會丢失了。
	}
			
}
           

MainActivity.java

package com.example.databasetest;

import java.io.File;

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

public class MainActivity extends Activity {

	private MyDatabaseHelper dbHelper;
	
	public static final String ExtSD_PATH = Environment.getExternalStorageDirectory().getPath();
	public static final String SYS_PATH = ExtSD_PATH + "/HC-DT5X"; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
//		String string = Environment.getExternalStorageDirectory().getPath();
		//判斷檔案夾是否存在
		 File sysFolder = new File(SYS_PATH);          
	        if (!sysFolder.exists()){  
	        	sysFolder.mkdirs();  
	        } 
		
		dbHelper = new MyDatabaseHelper(this, SYS_PATH + "/BookStore.db", null, 3);
		Button createDatabase = (Button) findViewById(R.id.create_database);
		createDatabase.setOnClickListener(new OnClickListener() {
		@Override
		public void onClick(View v) {
		dbHelper.getWritableDatabase();
		}
		});
		
		Button addData = (Button) findViewById(R.id.add_data);
		
		addData.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				SQLiteDatabase db = dbHelper.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);
//				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" });
				
	//			Toast.makeText(MainActivity.this, "Insert succeeded", Toast.LENGTH_SHORT).show();
			}
		});
		
		Button updateData = (Button) findViewById(R.id.update_data);
		updateData.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SQLiteDatabase db = dbHelper.getWritableDatabase();
				ContentValues values = new ContentValues();
				values.put("price", 10.99);
				db.update("Book", values, "name = ?", new String[] { "The Da Vinci Code" });		//更新資料庫
//				db.execSQL("update Book set price = ? where name = ?", new String[] { "10.99",
//				"The Da Vinci Code" });
//				Toast.makeText(MainActivity.this, "Update succeeded", Toast.LENGTH_SHORT).show();
			}
		});
		
		Button deleteButton = (Button) findViewById(R.id.delete_data);
		deleteButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			db.delete("Book", "pages > ?", new String[] { "500" });										//删除資料
//			db.execSQL("delete from Book where pages > ?", new String[] { "500" });
//			Toast.makeText(MainActivity.this, "Del succeeded", Toast.LENGTH_SHORT).show();
			}
		});
		
		Button queryButton = (Button) findViewById(R.id.query_data);
		queryButton.setOnClickListener(new OnClickListener() {
		@Override
		public void onClick(View v) {
			SQLiteDatabase db = dbHelper.getWritableDatabase();
//			db.rawQuery("select * from Book", null);
			// 查詢Book表中所有的資料
			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"));
					Log.d("MainActivity", "book name is " + name);
					Log.d("MainActivity", "book author is " + author);
					Log.d("MainActivity", "book pages is " + pages);
					Log.d("MainActivity", "book price is " + price);
				} while (cursor.moveToNext());
			}
			cursor.close();
			}
		});
		
		//事物的應用
		Button replaceData = (Button) findViewById(R.id.replace_data);
		replaceData.setOnClickListener(new OnClickListener() {
		@Override
		public void onClick(View v) {
			SQLiteDatabase db = dbHelper.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(); // 結束事務
			}
			}
		});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}


           

注意:

主要的流程都完成了,但并不代表所有工作都完成了,現在最重要的一步是别忘記在AndroidManifest.xml中給檔案添加可讀和可寫的權限(因為資料庫本身也是檔案哦),當然如果你已經添加過那就沒有問題了,下邊紅色的字型:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/></span>
           

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.databasetest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
     <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.INTERNET" />
    
    
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.databasetest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
           

到這裡所有工作都已經完成了,可以手動去運作試試哦,具體代碼我會傳到csdn上。。。