android中SQLlite數據庫中對應的SQL數據庫的查詢 query ,delete,insert

這篇文章主要介紹了Android中的SQL查詢語句LIKE綁定參數問題解決辦法,本文使用的是sqlite數據庫,需要的朋友可以參考下
由於考慮到數據庫的安全性,不被輕易SQL注入,執行查詢語句時,一般不使用直接拼接的語句,而是使用參數傳遞的方法。然後在使用參數傳遞的方法中時,發現當使用like方式查詢數據時,很容易出現一個問題。
錯誤案例:
複製代碼 代碼如下:
String myname = "abc";
String sql = "select * from mytable where name like '?%'";
Cursor cursor = db.rawQuery(sql, new String[]{myname};

運行提示如下錯誤:
複製代碼 代碼如下:
java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
根據錯誤提示可知,sql語句中的?號沒有被識別出來,從而new String[]{myname}沒法替代sql中的?號。?號沒有被識別出來的原因估計是?號外有單引號,但是在sql中like語句的值和%號需要用引號圍着。
爲了解決sql中?號無法識別,必須去掉?號外的引號,那麼%號也需要去掉。所以,得在後面代替?號的參數中添加上%號。
所以,正確的案例如下:
複製代碼 代碼如下:

String myname = "abc";
String sql = "select * from mytable where name like ?";
Cursor cursor = db.rawQuery(sql, new String[]{myname+"%"};
select * from mytable where name like abc%
如果是:
String myname = "abc";
String sql = "select * from mytable where name like ?";
Cursor cursor = db.rawQuery(sql, new String[]{"%"+myname+"%"};
select * from mytable where name like %abc%
可能有人會問爲什麼不用添加引號,因爲參數代替?號時,自動以字符串的形式代替的。 

1. public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)  
下面再看看query函數的原型,只讀取關心的字段,應該可以提高一點速度
query(Uri uri, String[] projection, String selection,
 String[] selectionArgs, String sortOrder)
projection:是需要讀取的字段
selection:是數據檢索的條件
selectionArgs:是數據檢索條件的參數
sortOrder:是排序的字段
解釋一下:假如一條sql語句如下:
select *  from anyTable where var=’const’
那麼anyTable就是uri,*就是projection,selection是“var=?”,selectionArgs寫成這樣:new String[]{‘const‘}
至於最後一個就簡單了,就是排序方式。

例子1:
select * from wy_table where name like %abc%;
 String selection = "name  like ?  ";
  String[] selectionArgs ={"%"+s.toString()+"%"};
 cursor=database.query("wy_table", null, selection,selectionArgs , null, null,null);
例子2:
select * from wy_table where name like %abc% or mobilephone like "abc";
我們可以定義如下:
  String selection = "name  like ? or mobilePhone like ? ";
  String[] selectionArgs ={"%"+s.toString()+"%","%"+s.toString()+"%"};
 cursor=database.query("wy_table", null, selection,selectionArgs , null, null,null);
s.toString()表示的是你要查找的字符串,s是一個Editedit編輯框類型,s.toString()表示得到該編輯框的字符串的值就相當於字符串"abc"。
 
   
 
SQL模糊查詢,使用like比較字,加上SQL裏的通配符,請參考以下:
1、LIKE'Mc%' 將搜索以字母 Mc 開頭的所有字符串(如 McBadden)。 
2、LIKE'%inger' 將搜索以字母 inger 結尾的所有字符串(如 Ringer、Stringer)。 
3、LIKE'%en%' 將搜索在任何位置包含字母 en 的所有字符串(如 Bennet、Green、McBadden)。 
4、LIKE'_heryl' 將搜索以字母 heryl 結尾的所有六個字母的名稱(如 Cheryl、Sheryl)。 
5、LIKE'[CK]ars[eo]n' 將搜索下列字符串:Carsen、Karsen、Carson 和 Karson(如 Carson)。 
6、LIKE'[M-Z]inger' 將搜索以字符串 inger 結尾、以從 M 到 Z 的任何單個字母開頭的所有名稱(如 Ringer)。 

7、LIKE'M[^c]%' 將搜索以字母 M 開頭,並且第二個字母不是 c 的所有名稱(如MacFeather)
查詢內容大都是中文(nvarchar),按照常規的"SELECT * FROM table WHERE column LIKE '%內容%'"總是查詢不到任何結果,而英文則沒有問題。覺得應該是字符編碼的問題,但在SQL Manager中沒有找到相應的設置項,後來發現在字符串前添加一個N,問題解決,瞭解發現添加N後表示在N以後的數據是Unicode類型的編碼方式。
查詢語句改爲"SELECT * FROM table WHERE column LIKE N'%內容%'",中文模糊查詢成功!
1、SQLiteDataBase對象的query()接口:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs,
                               String groupBy, String having,String orderBy,String limit)
Query the given table, returning a Cursor over the result set.

Parameters
table The table name to compile the query against.(要查詢的表名.)
columns A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.(想要顯示的列,若爲空則返回所有列,不建議設置爲空,如果不是返回所有列)
selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.(where子句,聲明要返回的行的要求,如果爲空則返回表的所有行。)
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.( where子句對應的條件值)
groupBy A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.(分組方式,若爲空則不分組.)
having A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.(having條件,若爲空則返回全部(不建議))
orderBy How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.(排序方式,爲空則爲默認排序方式)
limit Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.(限制返回的記錄的條數,爲空則不限制)
Returns
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
示例:
ContentValues cv = new ContentValues();
String[] args = {String.valueOf("a")};
query("user", new String[] { "username","password" },"username=?", args, null,null, null, null);

2、SQLiteDataBase對象的insert()接口:
public long insert (String table, String nullColumnHack, ContentValues values)

Convenience method for inserting a row into the database.

Parameters
table the table to insert the row into(要插入數據的表的名稱)
nullColumnHack optional; may be null. SQL doesn't allow inserting a completely empty row without naming at least one column name. If your provided valuesis empty, no column names are known and an empty row can't be inserted. If not set to null, the nullColumnHack parameter provides the name of nullable column name to explicitly insert a NULL into in the case where your values is empty.( 當values參數爲空或者裏面沒有內容的時候,我們insert是會失敗的(底層數據庫不允許插入一個空行),爲了防止這種情況,我們要在這裏指定一個 列名,到時候如果發現將要插入的行爲空行時,就會將你指定的這個列名的值設爲null,然後再向數據庫中插入。)
values this map contains the initial column values for the row. The keys should be the column names and the values the column values(一個ContentValues對象,類似一個map.通過鍵值對的形式存儲值。)
Returns
the row ID of the newly inserted row, or -1 if an error occurred
示例:
ContentValues cv = new ContentValues();
cv.put("username", "a");
cv.put("password", "b");
insert("user", null, cv);
 
 
3、SQLiteDataBase對象的update()接口:
public int update (String table, ContentValues values, String whereClause, String[] whereArgs)

Convenience method for updating rows in the database.

Parameters
table the table to update in(要更新的表名)
values a map from column names to new column values. null is a valid value that will be translated to NULL.(一個ContentValues對象,類似一個map.通過鍵值對的形式存儲值。)
whereClause


whereArgs the optional WHERE clause to apply when updating. Passing null will update all rows.(可選的where語句)

the group of args to deal with(whereClause語句中表達式的?佔位參數列表)
Returns
the number of rows affected
ContentValues cv = new ContentValues();
cv.put("username", "c");
cv.put("password", "d");
String[] args = {String.valueOf("a")};
update("user", cv, "username=?",args)
 
 
4、SQLiteDataBase對象的delete()接口:
public int delete (String table, String whereClause, String[] whereArgs)

Convenience method for deleting rows in the database.

Parameters
table the table to delete from
whereClause

whereArgs the optional WHERE clause to apply when deleting. Passing null will delete all rows.(可選的where語句)
the optional WHERE clause to apply when updating. Passing null will update all rows.(whereClause語句中表達式的?佔位參數列表)
Returns
the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause.
示例:
ContentValues cv = new ContentValues();
String[] args = {String.valueOf("c")};
delete("user", "username=?", args);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章