Android連載36-查詢數據、使用原生SQL以及事務的使用

1、查詢數據

  • android的查詢數據庫操做很複雜,SQLiteDatabase使用了query方法來進行查找數據,內含不少參數,咱們來看一下
query()方法參數 對應SQL部分 描述
table from table_name 表名
colums select colum1,colum2 要查詢的列名
selection where column = value 約束條件
selectionArgs - 爲where中的佔位符提供具體的值
groupBy group by column 須要分組的列
having having column = value 對分組後的結果進一步約束
orderBy order by column1,column2 排序方式
  • 調用後會返回一個Cursor對象,查詢到的全部對象都會從這裏取出來。
  • 修改activity_main.xml
<LinearLayout>
..........省略代碼...........
	<Button
	    android:id="@+id/query_data"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:text="Query data"
	    />

</LinearLayout>
  • 添加了一個按鈕用於查詢數據,而後修改MainActivity.java
package com.example.databasetest;

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

public class MainActivity extends Activity {
	
	private MyDatabaseHelper dbHelper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		dbHelper = new MyDatabaseHelper(this,"BookStore.db",null,2);
...............省略代碼..........................
		Button queryButton = (Button)findViewById(R.id.query_data);
		queryButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SQLiteDatabase db = dbHelper.getWritableDatabase();
				//查詢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();
			}
		});
	}
}
  • 獲得Cursor對象以後,調用moveToFirst()方法來把指針移到第一行的位置,而後進入循環,循環條件是moveToNext(),直到指針指到了空的位置才中止;循環內部就是cursor的getObject的方法,來取到對應Object類型的值,方法內傳入的參數就是cursor.get+列名;最後關閉cursor
    36.1
    36.2

2、使用SQL操做數據庫

  • 若是不想使用android提供的方法,就像使用原生的SQL語言,那麼也內置了方法來實現
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.execSQL("insert into Book(name,author,pages,prices) values(?,?,?,?)",new String[] {"xiaoming","Dan Brown","454","16.69");
//相似預編譯的方法
  • 如上代碼是插入數據的方法,對應的更新數據方法爲:execSQL,刪除數據:execSQL,查詢數據:rawQuery

3、SQLite最佳實踐

使用事務

  • 刪除舊數據,添加新數據,這兩個操做都在一個事務中,咱們修改activity_main.xml
<LinearLayout>
..........省略代碼...........
	<Button 
	    android:id="@+id/replace_data"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:text="Replace data"
	    />
</LinearLayout>
  • 修改MainActivity.java,在最後添加以下按鈕綁定的事件
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();//結束事務
				}
			}
		});

36.3

4、源碼:

相關文章
相關標籤/搜索