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);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的示例程序,演示如何在Android应用使用SQLite数据库实现诗词的增删改查功能。 首先,在你的Android应用创建一个SQLiteOpenHelper类,该类将用于创建和管理数据库。下面是一个示例代码,你可以根据自己的需要进行修改: ``` public class PoemDbHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "poem.db"; private static final int DATABASE_VERSION = 1; public PoemDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { final String SQL_CREATE_POEM_TABLE = "CREATE TABLE " + PoemContract.PoemEntry.TABLE_NAME + " (" + PoemContract.PoemEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + PoemContract.PoemEntry.COLUMN_TITLE + " TEXT NOT NULL, " + PoemContract.PoemEntry.COLUMN_AUTHOR + " TEXT NOT NULL, " + PoemContract.PoemEntry.COLUMN_CONTENT + " TEXT NOT NULL" + ");"; db.execSQL(SQL_CREATE_POEM_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + PoemContract.PoemEntry.TABLE_NAME); onCreate(db); } } ``` 接下来,我们需要创建一个PoemContract类,该类定义了数据库表的结构。下面是一个示例代码: ``` public class PoemContract { public static final class PoemEntry implements BaseColumns { public static final String TABLE_NAME = "poem"; public static final String COLUMN_TITLE = "title"; public static final String COLUMN_AUTHOR = "author"; public static final String COLUMN_CONTENT = "content"; } } ``` 在应用,我们需要使用ContentValues对象来执行数据库操作。下面是一个示例代码,展示如何添加一首新诗: ``` PoemDbHelper dbHelper = new PoemDbHelper(context); SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(PoemContract.PoemEntry.COLUMN_TITLE, "静夜思"); values.put(PoemContract.PoemEntry.COLUMN_AUTHOR, "李白"); values.put(PoemContract.PoemEntry.COLUMN_CONTENT, "床前明月光,疑是地上霜。"); long newRowId = db.insert(PoemContract.PoemEntry.TABLE_NAME, null, values); ``` 要更新一首诗,可以使用以下代码: ``` SQLiteDatabase db = mDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(PoemContract.PoemEntry.COLUMN_TITLE, "新标题"); String selection = PoemContract.PoemEntry._ID + " = ?"; String[] selectionArgs = { String.valueOf(poemId) }; int count = db.update( PoemContract.PoemEntry.TABLE_NAME, values, selection, selectionArgs); ``` 要删除一首诗,可以使用以下代码: ``` SQLiteDatabase db = mDbHelper.getWritableDatabase(); String selection = PoemContract.PoemEntry._ID + " = ?"; String[] selectionArgs = { String.valueOf(poemId) }; int deletedRows = db.delete(PoemContract.PoemEntry.TABLE_NAME, selection, selectionArgs); ``` 最后,要查询诗歌,可以使用以下代码: ``` SQLiteDatabase db = mDbHelper.getReadableDatabase(); String[] projection = { PoemContract.PoemEntry._ID, PoemContract.PoemEntry.COLUMN_TITLE, PoemContract.PoemEntry.COLUMN_AUTHOR, PoemContract.PoemEntry.COLUMN_CONTENT }; String sortOrder = PoemContract.PoemEntry.COLUMN_TITLE + " DESC"; Cursor cursor = db.query( PoemContract.PoemEntry.TABLE_NAME, projection, null, null, null, null, sortOrder ); while(cursor.moveToNext()) { long itemId = cursor.getLong(cursor.getColumnIndexOrThrow(PoemContract.PoemEntry._ID)); String title = cursor.getString(cursor.getColumnIndexOrThrow(PoemContract.PoemEntry.COLUMN_TITLE)); String author = cursor.getString(cursor.getColumnIndexOrThrow(PoemContract.PoemEntry.COLUMN_AUTHOR)); String content = cursor.getString(cursor.getColumnIndexOrThrow(PoemContract.PoemEntry.COLUMN_CONTENT)); } ``` 上面的代码将返回所有诗歌的标题、作者和内容。你可以根据自己的需要进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值