【复习】使用 SQLiteDatabase 操作 SQLite 数据库
生活随笔
收集整理的這篇文章主要介紹了
【复习】使用 SQLiteDatabase 操作 SQLite 数据库
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Android提供了一個名為SQLiteDatabase的類,該類封裝了一些操作數據庫的API,使用該類可以完成對數據進行添加(Create)、查詢(Retrieve)、更新(Update)和刪除(Delete)操作(這些操作簡稱為CRUD)。對SQLiteDatabase的學習,我們應該重點掌握execSQL()和rawQuery()方法。 execSQL()方法可以執行insert、delete、update和CREATE TABLE之類有更改行為的SQL語句; rawQuery()方法用于執行select語句。?
execSQL()方法的使用例子:?
SQLiteDatabase db = ....;?
db.execSQL("insert into person(name, age) values('測試數據', 4)");?
db.close();?
執行上面SQL語句會往person表中添加進一條記錄,在實際應用中, 語句中的“測試數據”這些參數值會由用戶輸入界面提供,如果把用戶輸入的內容原樣組拼到上面的insert語句, 當用戶輸入的內容含有單引號時,組拼出來的SQL語句就會存在語法錯誤。要解決這個問題需要對單引號進行轉義,也就是把單引號轉換成兩個單引號。有些時候用戶往往還會輸入像“ & ”這些特殊SQL符號,為保證組拼好的SQL語句語法正確,必須對SQL語句中的這些特殊SQL符號都進行轉義,顯然,對每條SQL語句都做這樣的處理工作是比較煩瑣的。 SQLiteDatabase類提供了一個重載后的execSQL(String sql, Object[] bindArgs)方法,使用這個方法可以解決前面提到的問題,因為這個方法支持使用占位符參數(?)。使用例子如下:?
SQLiteDatabase db = ....;?
db.execSQL("insert into person(name, age) values(?,?)", new Object[]{"測試數據", 4}); ?
db.close();?
execSQL(String sql, Object[] bindArgs)方法的第一個參數為SQL語句,第二個參數為SQL語句中占位符參數的值,參數值在數組中的順序要和占位符的位置對應。?
?
public class DatabaseHelper extends SQLiteOpenHelper { ?
? ? //類沒有實例化,是不能用作父類構造器的參數,必須聲明為靜態 ?
? ? ? ? ?private static final String name = "itcast"; //數據庫名稱 ?
? ? ? ? ?private static final int version = 1; //數據庫版本 ?
? ? ? ? ?public DatabaseHelper(Context context) { ?
//第三個參數CursorFactory指定在執行查詢時獲得一個游標實例的工廠類,設置為null,代表使用系統默認的工廠類 ?
? ? ? ? ? ? ? ? super(context, name, null, version); ?
? ? ? ? ?} ?
? ? ? ? @Override public void onCreate(SQLiteDatabase db) { ?
? ? ? ? ? ? ? db.execSQL("CREATE TABLE IF NOT EXISTS person (personid integer primary key autoincrement, name varchar(20), age INTEGER)"); ? ??
? ? ? ? ?} ?
? ? ? ? @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { ?
? ? ? ? ? ? ? ?db.execSQL(" ALTER TABLE person ADD phone VARCHAR(12) NULL "); //往表中增加一列 ?
? ? // DROP TABLE IF EXISTS person 刪除表 ?
? ? ? ?} ?
} ?
//在實際項目開發中,當數據庫表結構發生更新時,應該避免用戶存放于數據庫中的數據丟失。 ?
SQLiteDatabase的rawQuery() 用于執行select語句,使用例子如下:
?SQLiteDatabase db = ....;?
Cursor cursor = db.rawQuery(“select * from person”, null);?
while (cursor.moveToNext()) {?
? ? int personid = cursor.getInt(0); //獲取第一列的值,第一列的索引從0開始?
? ? String name = cursor.getString(1);//獲取第二列的值?
? ? int age = cursor.getInt(2);//獲取第三列的值?
}?
cursor.close();?
db.close(); ?
rawQuery()方法的第一個參數為select語句;第二個參數為select語句中占位符參數的值,如果select語句沒有使用占位符,該參數可以設置為null。帶占位符參數的select語句使用例子如下:?
Cursor cursor = db.rawQuery("select * from person where name like ? and age=?", new String[]{"%傳智%", "4"});?
Cursor是結果集游標,用于對結果集進行隨機訪問,如果大家熟悉jdbc, 其實Cursor與JDBC中的ResultSet作用很相似。使用moveToNext()方法可以將游標從當前行移動到下一行,如果已經移過了結果集的最后一行,返回結果為false,否則為true。另外Cursor 還有常用的moveToPrevious()方法(用于將游標從當前行移動到上一行,如果已經移過了結果集的第一行,返回值為false,否則為true )、moveToFirst()方法(用于將游標移動到結果集的第一行,如果結果集為空,返回值為false,否則為true )和moveToLast()方法(用于將游標移動到結果集的最后一行,如果結果集為空,返回值為false,否則為true )。?
除了前面給大家介紹的execSQL()和rawQuery()方法, SQLiteDatabase還專門提供了對應于添加、刪除、更新、查詢的操作方法: insert()、delete()、update()和query() 。這些方法實際上是給那些不太了解SQL語法的菜鳥使用的,對于熟悉SQL語法的程序員而言,直接使用execSQL()和rawQuery()方法執行SQL語句就能完成數據的添加、刪除、更新、查詢操作。?
Insert()方法用于添加數據,各個字段的數據使用ContentValues進行存放。 ContentValues類似于MAP,相對于MAP,它提供了存取數據對應的put(String key, Xxx value)和getAsXxx(String key)方法, ?key為字段名稱,value為字段值,Xxx指的是各種常用的數據類型,如:String、Integer等。?
SQLiteDatabase db = databaseHelper.getWritableDatabase();?
ContentValues values = new ContentValues();?
values.put("name", "測試數據");?
values.put("age", 4);?
long rowid = db.insert(“person”, null, values);//返回新添記錄的行號,與主鍵id無關?
不管第三個參數是否包含數據,執行Insert()方法必然會添加一條記錄,如果第三個參數為空,會添加一條除主鍵之外其他字段值為Null的記錄。Insert()方法內部實際上通過構造insert SQL語句完成數據的添加,Insert()方法的第二個參數用于指定空值字段的名稱,相信大家對該參數會感到疑惑,該參數的作用是什么?是這樣的:如果第三個參數values 為Null或者元素個數為0, 由于Insert()方法要求必須添加一條除了主鍵之外其它字段為Null值的記錄,為了滿足SQL語法的需要, insert語句必須給定一個字段名,如:insert into person(name) values(NULL),倘若不給定字段名 , insert語句就成了這樣: insert into person() values(),顯然這不滿足標準SQL的語法。對于字段名,建議使用主鍵之外的字段,如果使用了INTEGER類型的主鍵字段,執行類似insert into person(personid) values(NULL)的insert語句后,該主鍵字段值也不會為NULL。如果第三個參數values 不為Null并且元素的個數大于0 ,可以把第二個參數設置為null。?
delete()方法的使用:?
SQLiteDatabase db = databaseHelper.getWritableDatabase();?
db.delete("person", "personid<?", new String[]{"2"});?
db.close();?
上面代碼用于從person表中刪除personid小于2的記錄。?
update()方法的使用:?
SQLiteDatabase db = databaseHelper.getWritableDatabase();?
ContentValues values = new ContentValues();?
values.put(“name”, “測試數據”);//key為字段名,value為值?
db.update("person", values, "personid=?", new String[]{"1"}); ?
db.close();?
上面代碼用于把person表中personid等于1的記錄的name字段的值改為“測試數據”。?
query()方法實際上是把select語句拆分成了若干個組成部分,然后作為方法的輸入參數:?
SQLiteDatabase db = databaseHelper.getWritableDatabase();?
Cursor cursor = db.query("person", new String[]{"personid,name,age"}, "name like ?", new String[]{"%傳智%"}, null, null, "personid desc", "1,2");?
while (cursor.moveToNext()) {?
? ? ? ? ?int personid = cursor.getInt(0); //獲取第一列的值,第一列的索引從0開始?
? ? ? ? String name = cursor.getString(1);//獲取第二列的值?
? ? ? ? int age = cursor.getInt(2);//獲取第三列的值?
}?
cursor.close();?
db.close(); ?
上面代碼用于從person表中查找name字段含有“傳智”的記錄,匹配的記錄按personid降序排序,對排序后的結果略過第一條記錄,只獲取2條記錄。?
query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit)方法各參數的含義:?
table:表名。相當于select語句from關鍵字后面的部分。如果是多表聯合查詢,可以用逗號將兩個表名分開。?
columns:要查詢出來的列名。相當于select語句select關鍵字后面的部分。?
selection:查詢條件子句,相當于select語句where關鍵字后面的部分,在條件子句允許使用占位符“?”?
selectionArgs:對應于selection語句中占位符的值,值在數組中的位置與占位符在語句中的位置必須一致,否則就會有異常。?
groupBy:相當于select語句group by關鍵字后面的部分?
having:相當于select語句having關鍵字后面的部分?
orderBy:相當于select語句order by關鍵字后面的部分,如:personid desc, age asc;?
limit:指定偏移量和獲取的記錄數,相當于select語句limit關鍵字后面的部分。?
package com.zyq.db; ?
import android.app.Activity; ?
import android.os.Bundle; ?
public class MainActivity extends Activity ??
{ ?
? ? @Override ?
? ? public void onCreate(Bundle savedInstanceState) ??
? ? { ?
? ? ? ? super.onCreate(savedInstanceState); ?
? ? ? ? setContentView(R.layout.main); ?
? ? } ?
} ?
package com.zyq.db; ?
import java.util.List; ?
import android.test.AndroidTestCase; ?
import android.util.Log; ?
import com.zyq.service.DBOpenHelper; ?
import com.zyq.service.PersonService; ?
import com.zyq.voo.Person; ?
??
/**?
?* 測試方法 通過Junit 單元測試?
?* 1.>實例化測試類?
?* 2.>把與應用有關的上下文信息傳入到測試類實例?
?* 3.>運行測試方法 ?
?* @author Administrator?
?*?
?*/ ?
public class PersonServiceTest extends AndroidTestCase ?
{ ?
? ? private final static String TAG="PersonServiceTest"; ?
? ? ??
? ? /**?
? ? ?* 測試創建數據庫?
? ? ?* @throws Throwable?
? ? ?*/ ?
? ? public void testCreateDB() throws Throwable ?
? ? { ?
? ? ? ? DBOpenHelper dbOpenHelper=new DBOpenHelper(this.getContext()); ?
? ? ? ? dbOpenHelper.getReadableDatabase(); //Create and/or open a database. ?
? ? } ?
? ? /**?
? ? ?* 測試新增一條記錄?
? ? ?* @throws Throwable?
? ? ?*/ ?
? ? public void testSave() throws Throwable ?
? ? { ?
? ? ? ? PersonService personService=new PersonService(this.getContext()); ?
? ? ? ? personService.save(new Person("zhangsan","1360215320")); ?
? ? ? ? personService.save(new Person("lisi","1123")); ?
? ? ? ? personService.save(new Person("lili","232")); ?
? ? ? ? personService.save(new Person("wangda","123123")); ?
? ? ? ? personService.save(new Person("laozhu","234532")); ?
? ? } ?
? ? /**?
? ? ?* 查找一條記錄?
? ? ?* @throws Throwable?
? ? ?*/ ?
? ? public void testFind() throws Throwable ?
? ? { ?
? ? ? ? PersonService personService=new PersonService(this.getContext()); ?
? ? ? ? Person person=personService.find(1); ?
? ? ? ? Log.i(TAG,person.toString()); ?
? ? } ?
? ? /**?
? ? ?* 測試更新一條記錄?
? ? ?* @throws Throwable?
? ? ?*/ ?
? ? public void testUpdate() throws Throwable ?
? ? { ?
? ? ? ? PersonService personService=new PersonService(this.getContext()); ?
? ? ? ? Person person=personService.find(1); ?
? ? ? ? person.setName("lisi"); ?
? ? ? ? personService.update(person); ?
? ? } ?
? ? /**?
? ? ?* 測試得到所有記錄數?
? ? ?* @throws Throwable?
? ? ?*/ ?
? ? public void testGetCount() throws Throwable ?
? ? { ?
? ? ? ? PersonService personService=new PersonService(this.getContext()); ?
? ? ? ? Log.i(TAG, personService.getCount()+"********"); ?
? ? } ?
? ? /**?
? ? ?* 測試分頁?
? ? ?* @throws Throwable?
? ? ?*/ ?
? ? public void testScroll() throws Throwable ?
? ? { ?
? ? ? ? PersonService personService=new PersonService(this.getContext()); ?
? ? ? ? List<Person> persons=personService.getScrollData(3, 3); ?
? ? ? ? for(Person person:persons) ?
? ? ? ? { ?
? ? ? ? ? ? Log.i(TAG, person.toString()); ?
? ? ? ? } ?
? ? } ?
? ? /**?
? ? ?* 測試刪除一條記錄?
? ? ?* @throws Throwable?
? ? ?*/ ?
? ? public void testDelete() throws Throwable ?
? ? { ?
? ? ? ? PersonService personService=new PersonService(this.getContext()); ?
? ? ? ? personService.delete(5); ?
? ? } ?
} ?
package com.zyq.service; ?
import android.content.Context; ?
import android.database.sqlite.SQLiteDatabase; ?
import android.database.sqlite.SQLiteOpenHelper; ?
public class DBOpenHelper extends SQLiteOpenHelper ?
{ ?
? ? /**?
? ? ?* 如果想額外的增加一個字段(需求)?
? ? ?* 可以把版本號更改掉 但必須 >=1?
? ? ?* 更改版本號之后 會根據版本號判斷是不是上次創建的時候 (目前的版本號和傳入的版本號是否一致 )?
? ? ?* 如果不是會執行 onUpgrade() 方法?
? ? ?* @param context?
? ? ?*/ ?
? ? public DBOpenHelper(Context context) ?
? ? { ?
? ? ? ? super(context, "zyq.db", null, 2); ?
? ? } ?
? ? /**?
? ? ?* 在數據庫創建的時候第一個調用的方法?
? ? ?* 適合創建表結構?
? ? ?*/ ?
? ? @Override ?
? ? public void onCreate(SQLiteDatabase db) ?
? ? { ?
? ? ? ? db.execSQL("CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))");//創建表 ?
? ? } ?
? ? /**?
? ? ?* 更新表結構 在數據庫版本號發生改變的時候調用?
? ? ?* 應用升級 ?
? ? ?*/ ?
? ? @Override ?
? ? public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) ?
? ? { ?
? ? ? ? db.execSQL("ALTER TABLE person ADD phone VARCHAR(12) NULL "); //往表中增加一列 ?
? ? } ?
} ?
<?xml version="1.0" encoding="utf-8"?> ?
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ?
? ? ? package="com.zyq.db" ?
? ? ? android:versionCode="1" ?
? ? ? android:versionName="1.0"> ?
? ? <application android:icon="@drawable/icon" android:label="@string/app_name"> ?
? ? <uses-library android:name="android.test.runner" /> ?
? ? ? ? <activity android:name=".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> ?
? ? <uses-sdk android:minSdkVersion="8" /> ?
? ? <instrumentation android:name="android.test.InstrumentationTestRunner" ?
? ? ? ? android:targetPackage="com.zyq.db" android:label="Tests for My App" /> ?
</manifest> ??
package com.zyq.service; ?
import java.util.ArrayList; ?
import java.util.List; ?
import android.content.Context; ?
import android.database.Cursor; ?
import android.database.sqlite.SQLiteDatabase; ?
import com.zyq.voo.Person; ?
public class PersonService ?
{ ?
? ? private DBOpenHelper helper; ?
? ? public PersonService(Context context) ?
? ? { ?
? ? ? ? helper=new DBOpenHelper(context); ?
? ? } ?
? ? /**?
? ? ?* 新增一條記錄?
? ? ?* @param person?
? ? ?*/ ?
? ? public void save(Person person) ?
? ? { ?
? ? ? ? SQLiteDatabase db=helper.getWritableDatabase();//Create and/or open a database that will be used for reading and writing ?
? ? ? ? db.execSQL("INSERT INTO person(name,phone) values(?,?)",new Object[]{person.getName().trim(),person.getPhone().trim()});//使用占位符進行轉譯 ?
// ? ? ?db.close(); ?不關數據庫連接 。可以提高性能 因為創建數據庫的時候的操作模式是私有的。 ?
// ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?代表此數據庫,只能被本應用所訪問 單用戶的,可以維持長久的鏈接 ?
? ? } ??
? ? /**?
? ? ?* 更新某一條記錄?
? ? ?* @param person?
? ? ?*/ ?
? ? public void update(Person person) ?
? ? { ?
? ? ? ? SQLiteDatabase db=helper.getWritableDatabase(); ?
? ? ? ? db.execSQL("update person set phone=?,name=? where personid=?", ?
? ? ? ? ? ? ? ? ? ? new Object[]{person.getPhone().trim(),person.getName().trim(),person.getId()}); ?
? ? } ?
? ? /**?
? ? ?* 根據ID查詢某條記錄?
? ? ?* @param id?
? ? ?* @return?
? ? ?*/ ?
? ? public Person find(Integer id) ?
? ? { ?
? ? ? ? SQLiteDatabase db=helper.getReadableDatabase(); ?
? ? ? ? Cursor cursor=db.rawQuery("select * from person where personid=?", new String[]{id.toString()});//Cursor 游標和 ResultSet 很像 ?
? ? ? ? if(cursor.moveToFirst())//Move the cursor to the first row. This method will return false if the cursor is empty. ?
? ? ? ? { ?
? ? ? ? ? ? int personid=cursor.getInt(cursor.getColumnIndex("personid")); ?
? ? ? ? ? ? String name=cursor.getString(cursor.getColumnIndex("name")); ?
? ? ? ? ? ? String phone=cursor.getString(cursor.getColumnIndex("phone")); ?
? ? ? ? ? ? ??
? ? ? ? ? ? return new Person(personid,name,phone); ?
? ? ? ? } ?
? ? ? ? return null; ?
? ? } ?
? ? /**?
? ? ?* 刪除某一條記錄?
? ? ?* @param id?
? ? ?*/ ?
? ? public void delete(Integer id) ?
? ? { ?
? ? ? ? SQLiteDatabase db=helper.getWritableDatabase(); ?
? ? ? ? db.execSQL("delete from person where personid=?", ?
? ? ? ? ? ? ? ? ? ? new Object[]{id}); ?
? ? } ?
? ? ??
? ? /**?
? ? ?* 得到記錄數?
? ? ?* @return?
? ? ?*/ ?
? ? public long getCount() ?
? ? { ?
? ? ? ? SQLiteDatabase db=helper.getReadableDatabase(); ?
? ? ? ? Cursor cursor=db.rawQuery("select count(*) from person", null); ?
? ? ? ? cursor.moveToFirst(); ?
? ? ? ? return cursor.getLong(0); ?
? ? } ?
? ? /**?
? ? ?* 分頁查詢方法 SQL語句跟MySQL的語法一樣?
? ? ?* @return?
? ? ?*/ ?
? ? public List<Person> getScrollData(int offset,int maxResult) ?
? ? { ?
? ? ? ? List<Person> persons=new ArrayList<Person>(); ?
? ? ? ? SQLiteDatabase db=helper.getReadableDatabase(); ?
? ? ? ? Cursor cursor=db.rawQuery("select * from person limit ?,?", ??
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? new String[]{String.valueOf(offset),String.valueOf(maxResult)}); ?
? ? ? ? while (cursor.moveToNext()) ?
? ? ? ? { ?
? ? ? ? ? ? int personid=cursor.getInt(cursor.getColumnIndex("personid")); ?
? ? ? ? ? ? String name=cursor.getString(cursor.getColumnIndex("name")); ?
? ? ? ? ? ? String phone=cursor.getString(cursor.getColumnIndex("phone")); ?
? ? ? ? ? ? ??
? ? ? ? ? ? persons.add(new Person(personid,name,phone)); ?
? ? ? ? } ?
? ? ? ? ??
? ? ? ? return persons; ?
? ? } ?
} ?
package com.zyq.voo; ?
public class Person ?
{ ?
? ? private Integer id; ?
? ? private String name; ?
? ? private String phone; ?
? ? ??
? ? public Person(int personid, String name, String phone) ?
? ? { ?
? ? ? ? this.id=personid; ?
? ? ? ? this.name=name; ?
? ? ? ? this.phone=phone; ?
? ? } ?
? ? ??
? ? public Person(String name, String phone) ?
? ? { ?
? ? ? ? this.name = name; ?
? ? ? ? this.phone = phone; ?
? ? } ?
? ? public String toString() ?
? ? { ?
? ? ? ? return "Person [id=" + id + ", name=" + name + ", phone=" + phone + "]"; ?
? ? } ?
? ? public Integer getId() ?
? ? { ?
? ? ? ? return id; ?
? ? } ?
? ? public void setId(Integer id) ?
? ? { ?
? ? ? ? this.id = id; ?
? ? } ?
? ? public String getName() ?
? ? { ?
? ? ? ? return name; ?
? ? } ?
? ? public void setName(String name) ?
? ? { ?
? ? ? ? this.name = name; ?
? ? } ?
? ? public String getPhone() ?
? ? { ?
? ? ? ? return phone; ?
? ? } ?
? ? public void setPhone(String phone) ?
? ? { ?
? ? ? ? this.phone = phone; ?
? ? } ?
? ? ??
? ? ??
? ? ??
} ? 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
execSQL()方法的使用例子:?
SQLiteDatabase db = ....;?
db.execSQL("insert into person(name, age) values('測試數據', 4)");?
db.close();?
執行上面SQL語句會往person表中添加進一條記錄,在實際應用中, 語句中的“測試數據”這些參數值會由用戶輸入界面提供,如果把用戶輸入的內容原樣組拼到上面的insert語句, 當用戶輸入的內容含有單引號時,組拼出來的SQL語句就會存在語法錯誤。要解決這個問題需要對單引號進行轉義,也就是把單引號轉換成兩個單引號。有些時候用戶往往還會輸入像“ & ”這些特殊SQL符號,為保證組拼好的SQL語句語法正確,必須對SQL語句中的這些特殊SQL符號都進行轉義,顯然,對每條SQL語句都做這樣的處理工作是比較煩瑣的。 SQLiteDatabase類提供了一個重載后的execSQL(String sql, Object[] bindArgs)方法,使用這個方法可以解決前面提到的問題,因為這個方法支持使用占位符參數(?)。使用例子如下:?
SQLiteDatabase db = ....;?
db.execSQL("insert into person(name, age) values(?,?)", new Object[]{"測試數據", 4}); ?
db.close();?
execSQL(String sql, Object[] bindArgs)方法的第一個參數為SQL語句,第二個參數為SQL語句中占位符參數的值,參數值在數組中的順序要和占位符的位置對應。?
?
public class DatabaseHelper extends SQLiteOpenHelper { ?
? ? //類沒有實例化,是不能用作父類構造器的參數,必須聲明為靜態 ?
? ? ? ? ?private static final String name = "itcast"; //數據庫名稱 ?
? ? ? ? ?private static final int version = 1; //數據庫版本 ?
? ? ? ? ?public DatabaseHelper(Context context) { ?
//第三個參數CursorFactory指定在執行查詢時獲得一個游標實例的工廠類,設置為null,代表使用系統默認的工廠類 ?
? ? ? ? ? ? ? ? super(context, name, null, version); ?
? ? ? ? ?} ?
? ? ? ? @Override public void onCreate(SQLiteDatabase db) { ?
? ? ? ? ? ? ? db.execSQL("CREATE TABLE IF NOT EXISTS person (personid integer primary key autoincrement, name varchar(20), age INTEGER)"); ? ??
? ? ? ? ?} ?
? ? ? ? @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { ?
? ? ? ? ? ? ? ?db.execSQL(" ALTER TABLE person ADD phone VARCHAR(12) NULL "); //往表中增加一列 ?
? ? // DROP TABLE IF EXISTS person 刪除表 ?
? ? ? ?} ?
} ?
//在實際項目開發中,當數據庫表結構發生更新時,應該避免用戶存放于數據庫中的數據丟失。 ?
SQLiteDatabase的rawQuery() 用于執行select語句,使用例子如下:
?SQLiteDatabase db = ....;?
Cursor cursor = db.rawQuery(“select * from person”, null);?
while (cursor.moveToNext()) {?
? ? int personid = cursor.getInt(0); //獲取第一列的值,第一列的索引從0開始?
? ? String name = cursor.getString(1);//獲取第二列的值?
? ? int age = cursor.getInt(2);//獲取第三列的值?
}?
cursor.close();?
db.close(); ?
rawQuery()方法的第一個參數為select語句;第二個參數為select語句中占位符參數的值,如果select語句沒有使用占位符,該參數可以設置為null。帶占位符參數的select語句使用例子如下:?
Cursor cursor = db.rawQuery("select * from person where name like ? and age=?", new String[]{"%傳智%", "4"});?
Cursor是結果集游標,用于對結果集進行隨機訪問,如果大家熟悉jdbc, 其實Cursor與JDBC中的ResultSet作用很相似。使用moveToNext()方法可以將游標從當前行移動到下一行,如果已經移過了結果集的最后一行,返回結果為false,否則為true。另外Cursor 還有常用的moveToPrevious()方法(用于將游標從當前行移動到上一行,如果已經移過了結果集的第一行,返回值為false,否則為true )、moveToFirst()方法(用于將游標移動到結果集的第一行,如果結果集為空,返回值為false,否則為true )和moveToLast()方法(用于將游標移動到結果集的最后一行,如果結果集為空,返回值為false,否則為true )。?
除了前面給大家介紹的execSQL()和rawQuery()方法, SQLiteDatabase還專門提供了對應于添加、刪除、更新、查詢的操作方法: insert()、delete()、update()和query() 。這些方法實際上是給那些不太了解SQL語法的菜鳥使用的,對于熟悉SQL語法的程序員而言,直接使用execSQL()和rawQuery()方法執行SQL語句就能完成數據的添加、刪除、更新、查詢操作。?
Insert()方法用于添加數據,各個字段的數據使用ContentValues進行存放。 ContentValues類似于MAP,相對于MAP,它提供了存取數據對應的put(String key, Xxx value)和getAsXxx(String key)方法, ?key為字段名稱,value為字段值,Xxx指的是各種常用的數據類型,如:String、Integer等。?
SQLiteDatabase db = databaseHelper.getWritableDatabase();?
ContentValues values = new ContentValues();?
values.put("name", "測試數據");?
values.put("age", 4);?
long rowid = db.insert(“person”, null, values);//返回新添記錄的行號,與主鍵id無關?
不管第三個參數是否包含數據,執行Insert()方法必然會添加一條記錄,如果第三個參數為空,會添加一條除主鍵之外其他字段值為Null的記錄。Insert()方法內部實際上通過構造insert SQL語句完成數據的添加,Insert()方法的第二個參數用于指定空值字段的名稱,相信大家對該參數會感到疑惑,該參數的作用是什么?是這樣的:如果第三個參數values 為Null或者元素個數為0, 由于Insert()方法要求必須添加一條除了主鍵之外其它字段為Null值的記錄,為了滿足SQL語法的需要, insert語句必須給定一個字段名,如:insert into person(name) values(NULL),倘若不給定字段名 , insert語句就成了這樣: insert into person() values(),顯然這不滿足標準SQL的語法。對于字段名,建議使用主鍵之外的字段,如果使用了INTEGER類型的主鍵字段,執行類似insert into person(personid) values(NULL)的insert語句后,該主鍵字段值也不會為NULL。如果第三個參數values 不為Null并且元素的個數大于0 ,可以把第二個參數設置為null。?
delete()方法的使用:?
SQLiteDatabase db = databaseHelper.getWritableDatabase();?
db.delete("person", "personid<?", new String[]{"2"});?
db.close();?
上面代碼用于從person表中刪除personid小于2的記錄。?
update()方法的使用:?
SQLiteDatabase db = databaseHelper.getWritableDatabase();?
ContentValues values = new ContentValues();?
values.put(“name”, “測試數據”);//key為字段名,value為值?
db.update("person", values, "personid=?", new String[]{"1"}); ?
db.close();?
上面代碼用于把person表中personid等于1的記錄的name字段的值改為“測試數據”。?
query()方法實際上是把select語句拆分成了若干個組成部分,然后作為方法的輸入參數:?
SQLiteDatabase db = databaseHelper.getWritableDatabase();?
Cursor cursor = db.query("person", new String[]{"personid,name,age"}, "name like ?", new String[]{"%傳智%"}, null, null, "personid desc", "1,2");?
while (cursor.moveToNext()) {?
? ? ? ? ?int personid = cursor.getInt(0); //獲取第一列的值,第一列的索引從0開始?
? ? ? ? String name = cursor.getString(1);//獲取第二列的值?
? ? ? ? int age = cursor.getInt(2);//獲取第三列的值?
}?
cursor.close();?
db.close(); ?
上面代碼用于從person表中查找name字段含有“傳智”的記錄,匹配的記錄按personid降序排序,對排序后的結果略過第一條記錄,只獲取2條記錄。?
query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit)方法各參數的含義:?
table:表名。相當于select語句from關鍵字后面的部分。如果是多表聯合查詢,可以用逗號將兩個表名分開。?
columns:要查詢出來的列名。相當于select語句select關鍵字后面的部分。?
selection:查詢條件子句,相當于select語句where關鍵字后面的部分,在條件子句允許使用占位符“?”?
selectionArgs:對應于selection語句中占位符的值,值在數組中的位置與占位符在語句中的位置必須一致,否則就會有異常。?
groupBy:相當于select語句group by關鍵字后面的部分?
having:相當于select語句having關鍵字后面的部分?
orderBy:相當于select語句order by關鍵字后面的部分,如:personid desc, age asc;?
limit:指定偏移量和獲取的記錄數,相當于select語句limit關鍵字后面的部分。?
package com.zyq.db; ?
import android.app.Activity; ?
import android.os.Bundle; ?
public class MainActivity extends Activity ??
{ ?
? ? @Override ?
? ? public void onCreate(Bundle savedInstanceState) ??
? ? { ?
? ? ? ? super.onCreate(savedInstanceState); ?
? ? ? ? setContentView(R.layout.main); ?
? ? } ?
} ?
package com.zyq.db; ?
import java.util.List; ?
import android.test.AndroidTestCase; ?
import android.util.Log; ?
import com.zyq.service.DBOpenHelper; ?
import com.zyq.service.PersonService; ?
import com.zyq.voo.Person; ?
??
/**?
?* 測試方法 通過Junit 單元測試?
?* 1.>實例化測試類?
?* 2.>把與應用有關的上下文信息傳入到測試類實例?
?* 3.>運行測試方法 ?
?* @author Administrator?
?*?
?*/ ?
public class PersonServiceTest extends AndroidTestCase ?
{ ?
? ? private final static String TAG="PersonServiceTest"; ?
? ? ??
? ? /**?
? ? ?* 測試創建數據庫?
? ? ?* @throws Throwable?
? ? ?*/ ?
? ? public void testCreateDB() throws Throwable ?
? ? { ?
? ? ? ? DBOpenHelper dbOpenHelper=new DBOpenHelper(this.getContext()); ?
? ? ? ? dbOpenHelper.getReadableDatabase(); //Create and/or open a database. ?
? ? } ?
? ? /**?
? ? ?* 測試新增一條記錄?
? ? ?* @throws Throwable?
? ? ?*/ ?
? ? public void testSave() throws Throwable ?
? ? { ?
? ? ? ? PersonService personService=new PersonService(this.getContext()); ?
? ? ? ? personService.save(new Person("zhangsan","1360215320")); ?
? ? ? ? personService.save(new Person("lisi","1123")); ?
? ? ? ? personService.save(new Person("lili","232")); ?
? ? ? ? personService.save(new Person("wangda","123123")); ?
? ? ? ? personService.save(new Person("laozhu","234532")); ?
? ? } ?
? ? /**?
? ? ?* 查找一條記錄?
? ? ?* @throws Throwable?
? ? ?*/ ?
? ? public void testFind() throws Throwable ?
? ? { ?
? ? ? ? PersonService personService=new PersonService(this.getContext()); ?
? ? ? ? Person person=personService.find(1); ?
? ? ? ? Log.i(TAG,person.toString()); ?
? ? } ?
? ? /**?
? ? ?* 測試更新一條記錄?
? ? ?* @throws Throwable?
? ? ?*/ ?
? ? public void testUpdate() throws Throwable ?
? ? { ?
? ? ? ? PersonService personService=new PersonService(this.getContext()); ?
? ? ? ? Person person=personService.find(1); ?
? ? ? ? person.setName("lisi"); ?
? ? ? ? personService.update(person); ?
? ? } ?
? ? /**?
? ? ?* 測試得到所有記錄數?
? ? ?* @throws Throwable?
? ? ?*/ ?
? ? public void testGetCount() throws Throwable ?
? ? { ?
? ? ? ? PersonService personService=new PersonService(this.getContext()); ?
? ? ? ? Log.i(TAG, personService.getCount()+"********"); ?
? ? } ?
? ? /**?
? ? ?* 測試分頁?
? ? ?* @throws Throwable?
? ? ?*/ ?
? ? public void testScroll() throws Throwable ?
? ? { ?
? ? ? ? PersonService personService=new PersonService(this.getContext()); ?
? ? ? ? List<Person> persons=personService.getScrollData(3, 3); ?
? ? ? ? for(Person person:persons) ?
? ? ? ? { ?
? ? ? ? ? ? Log.i(TAG, person.toString()); ?
? ? ? ? } ?
? ? } ?
? ? /**?
? ? ?* 測試刪除一條記錄?
? ? ?* @throws Throwable?
? ? ?*/ ?
? ? public void testDelete() throws Throwable ?
? ? { ?
? ? ? ? PersonService personService=new PersonService(this.getContext()); ?
? ? ? ? personService.delete(5); ?
? ? } ?
} ?
package com.zyq.service; ?
import android.content.Context; ?
import android.database.sqlite.SQLiteDatabase; ?
import android.database.sqlite.SQLiteOpenHelper; ?
public class DBOpenHelper extends SQLiteOpenHelper ?
{ ?
? ? /**?
? ? ?* 如果想額外的增加一個字段(需求)?
? ? ?* 可以把版本號更改掉 但必須 >=1?
? ? ?* 更改版本號之后 會根據版本號判斷是不是上次創建的時候 (目前的版本號和傳入的版本號是否一致 )?
? ? ?* 如果不是會執行 onUpgrade() 方法?
? ? ?* @param context?
? ? ?*/ ?
? ? public DBOpenHelper(Context context) ?
? ? { ?
? ? ? ? super(context, "zyq.db", null, 2); ?
? ? } ?
? ? /**?
? ? ?* 在數據庫創建的時候第一個調用的方法?
? ? ?* 適合創建表結構?
? ? ?*/ ?
? ? @Override ?
? ? public void onCreate(SQLiteDatabase db) ?
? ? { ?
? ? ? ? db.execSQL("CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))");//創建表 ?
? ? } ?
? ? /**?
? ? ?* 更新表結構 在數據庫版本號發生改變的時候調用?
? ? ?* 應用升級 ?
? ? ?*/ ?
? ? @Override ?
? ? public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) ?
? ? { ?
? ? ? ? db.execSQL("ALTER TABLE person ADD phone VARCHAR(12) NULL "); //往表中增加一列 ?
? ? } ?
} ?
<?xml version="1.0" encoding="utf-8"?> ?
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ?
? ? ? package="com.zyq.db" ?
? ? ? android:versionCode="1" ?
? ? ? android:versionName="1.0"> ?
? ? <application android:icon="@drawable/icon" android:label="@string/app_name"> ?
? ? <uses-library android:name="android.test.runner" /> ?
? ? ? ? <activity android:name=".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> ?
? ? <uses-sdk android:minSdkVersion="8" /> ?
? ? <instrumentation android:name="android.test.InstrumentationTestRunner" ?
? ? ? ? android:targetPackage="com.zyq.db" android:label="Tests for My App" /> ?
</manifest> ??
package com.zyq.service; ?
import java.util.ArrayList; ?
import java.util.List; ?
import android.content.Context; ?
import android.database.Cursor; ?
import android.database.sqlite.SQLiteDatabase; ?
import com.zyq.voo.Person; ?
public class PersonService ?
{ ?
? ? private DBOpenHelper helper; ?
? ? public PersonService(Context context) ?
? ? { ?
? ? ? ? helper=new DBOpenHelper(context); ?
? ? } ?
? ? /**?
? ? ?* 新增一條記錄?
? ? ?* @param person?
? ? ?*/ ?
? ? public void save(Person person) ?
? ? { ?
? ? ? ? SQLiteDatabase db=helper.getWritableDatabase();//Create and/or open a database that will be used for reading and writing ?
? ? ? ? db.execSQL("INSERT INTO person(name,phone) values(?,?)",new Object[]{person.getName().trim(),person.getPhone().trim()});//使用占位符進行轉譯 ?
// ? ? ?db.close(); ?不關數據庫連接 。可以提高性能 因為創建數據庫的時候的操作模式是私有的。 ?
// ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?代表此數據庫,只能被本應用所訪問 單用戶的,可以維持長久的鏈接 ?
? ? } ??
? ? /**?
? ? ?* 更新某一條記錄?
? ? ?* @param person?
? ? ?*/ ?
? ? public void update(Person person) ?
? ? { ?
? ? ? ? SQLiteDatabase db=helper.getWritableDatabase(); ?
? ? ? ? db.execSQL("update person set phone=?,name=? where personid=?", ?
? ? ? ? ? ? ? ? ? ? new Object[]{person.getPhone().trim(),person.getName().trim(),person.getId()}); ?
? ? } ?
? ? /**?
? ? ?* 根據ID查詢某條記錄?
? ? ?* @param id?
? ? ?* @return?
? ? ?*/ ?
? ? public Person find(Integer id) ?
? ? { ?
? ? ? ? SQLiteDatabase db=helper.getReadableDatabase(); ?
? ? ? ? Cursor cursor=db.rawQuery("select * from person where personid=?", new String[]{id.toString()});//Cursor 游標和 ResultSet 很像 ?
? ? ? ? if(cursor.moveToFirst())//Move the cursor to the first row. This method will return false if the cursor is empty. ?
? ? ? ? { ?
? ? ? ? ? ? int personid=cursor.getInt(cursor.getColumnIndex("personid")); ?
? ? ? ? ? ? String name=cursor.getString(cursor.getColumnIndex("name")); ?
? ? ? ? ? ? String phone=cursor.getString(cursor.getColumnIndex("phone")); ?
? ? ? ? ? ? ??
? ? ? ? ? ? return new Person(personid,name,phone); ?
? ? ? ? } ?
? ? ? ? return null; ?
? ? } ?
? ? /**?
? ? ?* 刪除某一條記錄?
? ? ?* @param id?
? ? ?*/ ?
? ? public void delete(Integer id) ?
? ? { ?
? ? ? ? SQLiteDatabase db=helper.getWritableDatabase(); ?
? ? ? ? db.execSQL("delete from person where personid=?", ?
? ? ? ? ? ? ? ? ? ? new Object[]{id}); ?
? ? } ?
? ? ??
? ? /**?
? ? ?* 得到記錄數?
? ? ?* @return?
? ? ?*/ ?
? ? public long getCount() ?
? ? { ?
? ? ? ? SQLiteDatabase db=helper.getReadableDatabase(); ?
? ? ? ? Cursor cursor=db.rawQuery("select count(*) from person", null); ?
? ? ? ? cursor.moveToFirst(); ?
? ? ? ? return cursor.getLong(0); ?
? ? } ?
? ? /**?
? ? ?* 分頁查詢方法 SQL語句跟MySQL的語法一樣?
? ? ?* @return?
? ? ?*/ ?
? ? public List<Person> getScrollData(int offset,int maxResult) ?
? ? { ?
? ? ? ? List<Person> persons=new ArrayList<Person>(); ?
? ? ? ? SQLiteDatabase db=helper.getReadableDatabase(); ?
? ? ? ? Cursor cursor=db.rawQuery("select * from person limit ?,?", ??
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? new String[]{String.valueOf(offset),String.valueOf(maxResult)}); ?
? ? ? ? while (cursor.moveToNext()) ?
? ? ? ? { ?
? ? ? ? ? ? int personid=cursor.getInt(cursor.getColumnIndex("personid")); ?
? ? ? ? ? ? String name=cursor.getString(cursor.getColumnIndex("name")); ?
? ? ? ? ? ? String phone=cursor.getString(cursor.getColumnIndex("phone")); ?
? ? ? ? ? ? ??
? ? ? ? ? ? persons.add(new Person(personid,name,phone)); ?
? ? ? ? } ?
? ? ? ? ??
? ? ? ? return persons; ?
? ? } ?
} ?
package com.zyq.voo; ?
public class Person ?
{ ?
? ? private Integer id; ?
? ? private String name; ?
? ? private String phone; ?
? ? ??
? ? public Person(int personid, String name, String phone) ?
? ? { ?
? ? ? ? this.id=personid; ?
? ? ? ? this.name=name; ?
? ? ? ? this.phone=phone; ?
? ? } ?
? ? ??
? ? public Person(String name, String phone) ?
? ? { ?
? ? ? ? this.name = name; ?
? ? ? ? this.phone = phone; ?
? ? } ?
? ? public String toString() ?
? ? { ?
? ? ? ? return "Person [id=" + id + ", name=" + name + ", phone=" + phone + "]"; ?
? ? } ?
? ? public Integer getId() ?
? ? { ?
? ? ? ? return id; ?
? ? } ?
? ? public void setId(Integer id) ?
? ? { ?
? ? ? ? this.id = id; ?
? ? } ?
? ? public String getName() ?
? ? { ?
? ? ? ? return name; ?
? ? } ?
? ? public void setName(String name) ?
? ? { ?
? ? ? ? this.name = name; ?
? ? } ?
? ? public String getPhone() ?
? ? { ?
? ? ? ? return phone; ?
? ? } ?
? ? public void setPhone(String phone) ?
? ? { ?
? ? ? ? this.phone = phone; ?
? ? } ?
? ? ??
? ? ??
? ? ??
} ? 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的【复习】使用 SQLiteDatabase 操作 SQLite 数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 都在买基金定投,它的优势有哪些呢
- 下一篇: mysql把游标数据存入表中_mysql