Android之採用execSQL與rawQuery方法完成資料的添刪改查操作詳解

來源:互聯網
上載者:User

使用 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 刪除表
}
}
//在實際項目開發中,當資料庫表結構發生更新時,應該避免使用者存放於數//據庫中的資料丟失。

複製代碼 代碼如下:/*
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語句中預留位置參數的值,參數值在數組中的順序要和預留位置的位置對應。
*/

複製代碼 代碼如下:/*
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;
}

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.