android-数据库SQLite相关
android平臺(tái)下的SQLite數(shù)據(jù)庫(kù)是一種輕量級(jí)數(shù)據(jù)庫(kù),支持標(biāo)準(zhǔn)的SQL語(yǔ)句。
本文將介紹
- android數(shù)據(jù)庫(kù)的創(chuàng)建
- 利用sql語(yǔ)句對(duì)數(shù)據(jù)庫(kù)增刪改查
- 系統(tǒng)api數(shù)據(jù)庫(kù)增刪改查
- 數(shù)據(jù)庫(kù)的事務(wù)
- 1,數(shù)據(jù)庫(kù)的創(chuàng)建
步驟:
- 寫一個(gè)類繼承SQLiteOpenHelper
- 在構(gòu)造函數(shù)中指定 數(shù)據(jù)庫(kù)名稱,游標(biāo)工廠, 版本號(hào)
- 初始化數(shù)據(jù)庫(kù),執(zhí)行g(shù)etWritableDatabase或getReadableDatabase, 創(chuàng)建或打開一個(gè)數(shù)據(jù)庫(kù).
-
onCreate里執(zhí)行SQL創(chuàng)建語(yǔ)句
-
?????? android平臺(tái)下數(shù)據(jù)庫(kù)的創(chuàng)建需要一個(gè)輔助類繼承SQLiteOpenHelper,并且需要重寫父類的構(gòu)造方法。
- /**
* 數(shù)據(jù)庫(kù)創(chuàng)建輔助類 寫一個(gè)類繼承SQLiteOpenHelper
*
* @author wgk
*
*/
public class PersonSQLiteOpenHelper extends SQLiteOpenHelper {public PersonSQLiteOpenHelper(Context context) { super(context, "PERSON.db", null, 1);//此處是super,直接調(diào)用父類的構(gòu)造方法
}/** * * 構(gòu)造方法,用于創(chuàng)建一個(gè)輔助類,用于打開/創(chuàng)建/管理一個(gè)數(shù)據(jù)庫(kù) * * @param context * 上下文 * @param name * 數(shù)據(jù)庫(kù)文件的名字 * @param factory * 游標(biāo)工廠 Cursor 游標(biāo)(指針), 本身并不存儲(chǔ)數(shù)據(jù). 保存數(shù)據(jù)庫(kù)的引用. * @param version * 數(shù)據(jù)庫(kù)版本 */ public PersonSQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); }@Override // 數(shù)據(jù)庫(kù)第一次被創(chuàng)建時(shí)調(diào)用,適合初始化操作 public void onCreate(SQLiteDatabase db) { // 創(chuàng)建表 db.execSQL("create table person (" + " _id integer primary key autoincrement, " + " name varchar(20), " + " age integer);"); }@Override // 數(shù)據(jù)庫(kù)更新時(shí)調(diào)用這個(gè)方法 // 用于執(zhí)行表的更新操作 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub
}}
??? 這個(gè)類僅僅是一個(gè)輔助類,若想使用數(shù)據(jù)庫(kù),還需要?jiǎng)?chuàng)建一個(gè)數(shù)據(jù)庫(kù)訪問(wèn)類PersonDAO。
-
2,對(duì)數(shù)據(jù)庫(kù)進(jìn)行增刪改查
- public class PersonDAO{private final Context context;private PersonSQLiteOpenHelper helper;public PersonDAO(Context context) {this.context = context;helper = new PersonSQLiteOpenHelper(context);}/*** @param name* @param age*/public void add(String name, int age) {SQLiteDatabase db = helper.getWritableDatabase();// db.execSQL("insert into person (name,age) values ('"+name+"',"+age+")");// 防止SQL注入db.execSQL("insert into person (name,values) values(?,?)",new Object[] { name, age });}/*** 根據(jù)名字刪除一條數(shù)據(jù)* * @param name*/public void delete(String name) {SQLiteDatabase db = helper.getWritableDatabase();db.execSQL("delete from person where name=?", new Object[] { name });}//根據(jù)名字更新年齡 public void update(int age, String name) {SQLiteDatabase db = helper.getWritableDatabase();db.execSQL("update person set age=? where name=?", new Object[] { age,name });}public void querySingleRecord(String nameStr) {SQLiteDatabase db = helper.getReadableDatabase();Cursor cursor = db.rawQuery("select * from person where name=?",new String[] { nameStr });if (cursor != null && cursor.moveToFirst()) {String _id = cursor.getString(0);String name = cursor.getString(1);String age = cursor.getString(2);System.out.println("_id: " + _id);System.out.println("name: " + name);System.out.println("age: " + age);cursor.close();}}/*** 查詢所有數(shù)據(jù)*/public void queryAll() {SQLiteDatabase db = helper.getReadableDatabase();Cursor cursor = db.rawQuery("select * form person", null);if (cursor != null && cursor.getCount() > 0) {while (cursor.moveToNext()) {int _id = cursor.getInt(cursor.getColumnIndex("_id"));String name = cursor.getString(cursor.getColumnIndex("name"));int age = cursor.getInt(cursor.getColumnIndex("age"));System.out.println("_id: " + _id);System.out.println("name: " + name);System.out.println("age: " + age);System.out.println("-----------------");}cursor.close();}}}
-
注意:在獲得數(shù)據(jù)庫(kù)輔助類對(duì)象時(shí),此時(shí)并未創(chuàng)建數(shù)據(jù)庫(kù),只有在輔助類對(duì)象調(diào)用getxxxxDatabase方法(創(chuàng)建可讀或者可寫的數(shù)據(jù)庫(kù))時(shí),才創(chuàng)建數(shù)據(jù)庫(kù)。
- //此時(shí)并未創(chuàng)建數(shù)據(jù)可 PersonSQLiteOpenHelper helper = new PersonSQLiteOpenHelper(getContext()); // 獲取一個(gè)可讀/可寫的數(shù)據(jù)庫(kù), 真正創(chuàng)建了數(shù)據(jù)庫(kù) helper.getWritableDatabase(); ? 3,使用goole的api操作數(shù)據(jù)庫(kù)
-
除了使用SQL語(yǔ)句來(lái)進(jìn)行增刪改查,還可以使用google提供的api。
//主要語(yǔ)句 // 增 db.insert("person", "name", values);// 刪db.delete("person", "name=?", new String[]{name});// 改db.update("person", values, "name=?", new String[]{name});//查Cursor cursor = db.query("person", // 表名null, // 要查詢列名 new String[]{name,age}"name = ?", // 查詢條件new String[]{nameStr},// 條件參數(shù)null, // 分組 null, // 分組null); // 排序使用google的api對(duì)PersonDAO進(jìn)行修改,如下
/*** 使用google提供的api來(lái)操作數(shù)據(jù)庫(kù)* * 數(shù)據(jù)庫(kù)訪問(wèn)對(duì)象* @author wgk**/ public class PersonDAO3 {private final Context context;private PersonSQLiteOpenHelper helper;public PersonDAO3(Context context){this.context=context;helper=new PersonSQLiteOpenHelper(context);}/*** 增加一條數(shù)據(jù)* @param name* @param age*/public void add(String name,int age){SQLiteDatabase db=helper.getWritableDatabase();ContentValues values=new ContentValues();values.put("name", name);values.put("age", age);//若需要插入一條空的數(shù)據(jù),需要指定任意一個(gè)列的名稱,以避免異常String nullColumnHack="null";long insert=db.insert("person", nullColumnHack, values);System.out.println(insert);}/*** 刪除一條數(shù)據(jù)根據(jù)名字* @param name*/public void delete(String name){SQLiteDatabase db=helper.getWritableDatabase();int delete=db.delete("person", "name=?", new String[]{name});System.out.println(delete); }/*** 更新年齡!根據(jù)名字* @param age* @param name*/public void update(int age,String name){SQLiteDatabase db=helper.getWritableDatabase();ContentValues values=new ContentValues();values.put("age", age);int update =db.update("person", values, "name=?", new String[]{name});System.out.println(update);}/*** 查!根據(jù)一個(gè)人的名字* @param name*/public void querySingleRecord(String nameStr){SQLiteDatabase db=helper.getReadableDatabase();Cursor cursor=db.query("person",null,//列名"name=?",//查詢條件new String[]{nameStr},//查詢參數(shù)null, //分組null,//分組null);//排序if(cursor!=null&&cursor.moveToFirst()){String _id=cursor.getString(0);String name=cursor.getString(1);String age=cursor.getString(2);System.out.println("_id: " + _id);System.out.println("name: " + name);System.out.println("age: " + age);//關(guān)閉cursor//關(guān)閉cursor//關(guān)閉cursor cursor.close();}}/*** 查詢所有數(shù)據(jù)*/public void queryAll(){SQLiteDatabase db=helper.getReadableDatabase();Cursor cursor=db.query("person",null,null,null, null, null, "_id DESC");//排序if(cursor!=null&&cursor.getCount()>0){while(cursor.moveToNext()){int _id=cursor.getInt(cursor.getColumnIndex("_id"));String name=cursor.getString(cursor.getColumnIndex("name"));int age=cursor.getInt(cursor.getColumnIndex("age"));System.out.println("_id: " + _id);System.out.println("name: " + name);System.out.println("age: " + age); }//關(guān)閉cursor//關(guān)閉cursor//關(guān)閉cursor cursor.close();}} }兩種方式的比較
1.利用SQL語(yǔ)句進(jìn)行增刪改查
優(yōu)點(diǎn):靈活, 根據(jù)需要進(jìn)行表的級(jí)聯(lián)查詢.缺點(diǎn):容易出錯(cuò). 沒有返回值
2.利用系統(tǒng)API增刪改查
優(yōu)點(diǎn):不容易出錯(cuò). 有返回值
缺點(diǎn):不靈活, 效率稍低, 拼接sql語(yǔ)句耗時(shí)
-------------------------------------------------我是分割線-------------------------------------------------
數(shù)據(jù)庫(kù)的事務(wù)(Transaction)
-
(安全性)銀行轉(zhuǎn)賬:
- 轉(zhuǎn)出,laowang 賬戶10000 -> 轉(zhuǎn)出1000 ->
- 轉(zhuǎn)入,xiaosan 賬戶 0 收到1000
?
-
(高效性)數(shù)據(jù)的插入:
-
- 提高數(shù)據(jù)庫(kù)操作效率, 大約提升6倍速度
- 打開一次數(shù)據(jù),
以laowang給xiaosan轉(zhuǎn)賬1000的例子寫一段demo如下
public class TransactionDemo extends AndroidTestCase{public void transactionDemo(){PersonSQLiteOpenHelper helper= new PersonSQLiteOpenHelper(getContext());//此時(shí)才真正創(chuàng)建數(shù)據(jù)庫(kù)SQLiteDatabase db=helper.getWritableDatabase();try{//開始事務(wù) db.beginTransaction();//轉(zhuǎn)出1000db.execSQL("update person set money=money-1000 where name=?", new Object[]{"laowang"});//在執(zhí)行至回滾點(diǎn)之前,并不會(huì)對(duì)數(shù)據(jù)庫(kù)進(jìn)行真的操作,一切都在內(nèi)存中進(jìn)行,只有執(zhí)行到回滾點(diǎn)之后,才會(huì)影響到數(shù)據(jù)庫(kù) //int i =1/0;//轉(zhuǎn)入1000db.execSQL("update person set money=money+1000 where name=?", new Object[]{"xiaosan"});//設(shè)置回滾點(diǎn) db.setTransactionSuccessful();}catch (Exception e){e.printStackTrace();}finally{db.endTransaction();}}?
總結(jié):
-------------------------------------------------基礎(chǔ)要像磐石!!!
轉(zhuǎn)載于:https://www.cnblogs.com/wgkupupup/p/4604991.html
總結(jié)
以上是生活随笔為你收集整理的android-数据库SQLite相关的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: [转]oracle中查询指定行数的记录
- 下一篇: JavaScript学习记录总结(四)—