創建3張表:(不用設主外鍵)
@Override
public void onCreate(SQLiteDatabase db) {
System.out.println("同時創建3張數據庫表");
db.execSQL("CREATE TABLE "+ "test1" +" (test1_id INTEGER PRIMARY KEY AUTOINCREMENT, test11desc VARCHAR(50), test12desc VARCHAR(50))");
db.execSQL("CREATE TABLE "+ "test2" +" (test2_id INTEGER PRIMARY KEY AUTOINCREMENT, test21desc VARCHAR(50), test22desc VARCHAR(50))");
db.execSQL("CREATE TABLE "+ "test3" +" (test3_id INTEGER PRIMARY KEY AUTOINCREMENT, test31desc VARCHAR(50), test32desc VARCHAR(50))");
}
多表查詢:
public void query(){
db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT test1.test11desc , test2.test22desc FROM test3 INNER JOIN test1 on test3.test3_id = test1.test1_id " + "INNER JOIN test2 on test3.test3_id = test2.test2_id " ,new String[]{});
while(cursor.moveToNext()){
String str = cursor.getString(cursor.getColumnIndex("test11desc"));
String str2 = cursor.getString(cursor.getColumnIndex("test22desc"));
System.out.println("查詢結果---->>"+str+"---"+str2); }
cursor.close();
db.close();
}
參考文章:http://blog.sina.com.cn/s/blog_4e32d6820100dvmc.html
源碼下載地址:http://download.csdn.net/detail/liubin8095/6401491
事務處理:
SQLite數據庫也使用了事務的處理方法,SQLiteDatabase類也提供了事務處理的API。
使用beginTransaction()方法開啟一個事務,然後執行數據庫操作,然後調用setTransactionSuccessful()方法設置事務成功標志。使用endTransaction結束提交事務。
還可以使用inTransaction()方法判斷是否處於一個事務中。
public void payment()
{
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
//開啟事務
db.beginTransaction();
try
{
//執行數據庫操作
db.execSQL("update person set amount=amount-10 where personid=?", new Object[]{1});
db.execSQL("update person set amount=amount+10 where personid=?", new Object[]{2});
//設置事務標志為成功,當結束事務時就會提交事務
db.setTransactionSuccessful();
}
catch(Exception e){
throw(e);
}
finally
{
//結束事務
db.endTransaction();
}
}