SQLIteDatabase.query method

本文详细解释了SQLiteDatabase中的query方法参数使用,包括tableColumns、whereClause、whereArgs的构造方式,通过示例代码帮助理解如何正确应用这些参数。


I am using the query method of SQLitDatabase. I am little bit confused about the parameters using in "query" method.

Cursor cursor = sqLiteDatabase.query(tableName, tableColumns, whereClause, whereArgs, groupBy, having, orderBy);

tableColumns - columns parameter is constructed as follows.
String[] columns = new String[]{KEY_ID, KEY_CONTENT};

If we need to get all the fields, how should the column parameter to be constructed. Do we need to include all the Field Names in String array?

whereClause - Confused about the construction of this parameter.

whereArgs - Confused about the construction of this parameter.

Can anybody help me

thanks in advance.

share | improve this question
 
Try a simple approach like this –  Imran Rana  May 15 '12 at 12:34
 
I know that method. But I am trying to learn how to implement query method instead of rawQuery. –  sree_iphonedev  May 15 '12 at 12:40

4 Answers

up vote 15 down vote accepted

tableColumns

  • null for all columns as in SELECT * FROM ...
  • new String[] { "column1", "column2", ... } for specific columns as in SELECT column1, column2 FROM ... - you can also put complex expressions here:
    new String[] { "(SELECT max(column1) FROM table1) AS max" } would give you a column named max holding the max value of column1

whereClause

  • the part you put after WHERE without that keyword, e.g. "column1 > 5"
  • should include ? for things that are dynamic, e.g. "column1=?" -> see whereArgs

whereArgs

  • specify the content that fills each ? in whereClause in the order they appear

the others

  • just like whereClause the statement after the keyword or null if you don't use it.

Example

String[] tableColumns = new String[] {
    "column1",
    "(SELECT max(column1) FROM table2) AS max"
};
String whereClause = "column1 = ? OR column1 = ?";
String[] whereArgs = new String[] {
    "value1",
    "value2"
};
String orderBy = "column1";
Cursor c = sqLiteDatabase.query("table1", tableColumns, whereClause, whereArgs,
        null, null, orderBy);

// since we have a named column we can do
int idx = c.getColumnIndex("max");

is equivalent to the following raw query

String queryString =
    "SELECT column1, (SELECT max(column1) FROM table1) AS max FROM table1 " +
    "WHERE column1 = ? OR column1 = ? ORDER BY column1";
sqLiteDatabase.rawQuery(queryString, whereArgs);

By using the Where/Bind -Args version you get automatically escaped values and you don't have to worry if input-data contains '.

Unsafe: String whereClause = "column1='" + value + "'";
Safe: String whereClause = "column1=?";

because if value contains a ' your statement either breaks and you get exceptions or does unintended things, for example value = "XYZ'; DROP TABLE table1;--" might even drop your table since the statement would become two statements and a comment:

SELECT * FROM table1 where column1='XYZ'; DROP TABLE table1;--'

using the args version XYZ'; DROP TABLE table1;-- would be escaped to 'XYZ''; DROP TABLE table1;--' and would only be treated as a value. Even if the ' is not intended to do bad things it is still quite common that people have it in their names or use it in texts, filenames, passwords etc. So always use the args version. (It is okay to build int and other primitives directly into whereClausethough)

share | improve this answer

桌面ANR了,anr日志如下: "main" prio=5 tid=1 TimedWaiting | group="main" sCount=1 ucsCount=0 flags=1 obj=0x74866a40 self=0x7186888c00 | sysTid=4011 nice=-10 cgrp=vip sched=1073741825/2 handle=0x722d2cc508 | state=S schedstat=( 162505346434 49475697797 580932 ) utm=11195 stm=5054 core=10 HZ=100 | stack=0x7ff3827000-0x7ff3829000 stackSize=8188KB | held mutexes= at sun.misc.Unsafe.park(Native method) - waiting on an unknown object at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:230) at android.database.sqlite.SQLiteConnectionPool.waitForConnection(SQLiteConnectionPool.java:848) at android.database.sqlite.SQLiteConnectionPool.acquireConnection(SQLiteConnectionPool.java:420) at android.database.sqlite.SQLiteSession.acquireConnection(SQLiteSession.java:916) at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:608) at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:67) at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37) at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46) at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1585) at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1519) at com.huawei.android.launcher.DatabaseHelper.getTableContent(DatabaseHelper.java:6076) at com.huawei.android.launcher.LauncherProvider.isCanUnionDate(LauncherProvider.java:681) at com.huawei.android.launcher.LauncherProvider.doNormalQuery(LauncherProvider.java:575) - locked <0x0bc72969> (a java.lang.Object) at com.huawei.android.launcher.LauncherProvider.query(LauncherProvider.java:530)
07-15
E/SQLiteDatabase: Error inserting map_no=1001 map_number=3 android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: map.map_no (code 2067 SQLITE_CONSTRAINT_UNIQUE) at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method) at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:938) at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:790) at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:88) at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1701) at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1570) at com.example.zl_h12pro_map.Sql.MapDatabaseManager.addMapWithCoords(MapDatabaseManager.java:79) at com.example.zl_h12pro_map.MainActivity.InsertMap(MainActivity.java:89) at com.example.zl_h12pro_map.MainActivity.onCreate(MainActivity.java:45) at android.app.Activity.performCreate(Activity.java:7994) at android.app.Activity.performCreate(Activity.java:7978) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:223) at android.app.ActivityThread.main(ActivityThread.java:7656) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
最新发布
12-02
jafrsho07010日志: 2025-09-23 18:10:10.394 6255-6255 JafCommonLog jp.or.jaf.syg D [app] [clientID] [172.16.1.15] [main:(ID=2)] [JafViewModel:navigate:586] Navigation: jafrsho07010 with data: JAFRSHO07010Model 2025-09-23 18:10:10.396 6255-6255 JafCommonLog jp.or.jaf.syg D [app] [clientID] [172.16.1.15] [main:(ID=2)] [JafNavDataManager:store:82] JafNavDataManager: オブジェクト保存 ID=b1af2f42-4aad-4e1d-afeb-dca429282e70, Type=JAFRSHO07010Model 2025-09-23 18:10:10.399 6255-6255 JafCommonLog jp.or.jaf.syg E [app] [clientID] [172.16.1.15] [main:(ID=2)] [JafNavHostKt:JafNavHost:invokeSuspend:125] 不正なナビゲーションルート: jafrsho07010, エラー: Navigation destination that matches route jafrsho07010?data_id=b1af2f42-4aad-4e1d-afeb-dca429282e70 cannot be found in the navigation graph ComposeNavGraph(0x0) startDestination={Destination(0xee073984) route=jafrsho01010} 2025-09-23 18:10:10.401 6255-6255 JafCommonLog jp.or.jaf.syg D [app] [clientID] [172.16.1.15] [main:(ID=2)] [JafNavDataManager:store:82] JafNavDataManager: オブジェクト保存 ID=99be5cf6-223f-4339-ad71-2b462cb08562, Type=JAFRSHO07010Model 2025-09-23 18:10:10.426 6255-6255 JafCommonLog jp.or.jaf.syg D [app] [clientID] [172.16.1.15] [main:(ID=2)] [JafNavDataManager:peek:148] JafNavDataManager: オブジェクト参照 ID=99be5cf6-223f-4339-ad71-2b462cb08562, Type=JAFRSHO07010Model 2025-09-23 18:10:10.480 1434-1498 SurfaceFlinger surfaceflinger D duplicate layer name: changing jp.or.jaf.syg/jp.or.jaf.syg.SygMainActivity to jp.or.jaf.syg/jp.or.jaf.syg.SygMainActivity#1 2025-09-23 18:10:10.483 6255-6255 jp.or.jaf.syg jp.or.jaf.syg W Accessing hidden method Landroid/view/RenderNode;->getScaleX()F (dark greylist, linking) 2025-09-23 18:10:10.512 1418-1418 allocator@2.0-s and...raphics.allocator@2.0-service I type=1400 audit(0.0:2128): avc: denied { read write } for path="/dev/fastpipe" dev="tmpfs" ino=7176 scontext=u:r:surfaceflinger:s0 tcontext=u:object_r:device:s0 tclass=chr_file permissive=1 2025-09-23 18:10:10.519 1434-1434 Binder:1434_3 surfaceflinger I type=1400 audit(0.0:2129): avc: denied { getattr } for path="/dev/fastpipe" dev="tmpfs" ino=7176 scontext=u:r:surfaceflinger:s0 tcontext=u:object_r:device:s0 tclass=chr_file permissive=1 2025-09-23 18:10:10.575 6255-6288 EGL_emulation jp.or.jaf.syg E tid 6288: eglSurfaceAttrib(1493): error 0x3009 (EGL_BAD_MATCH) 2025-09-23 18:10:10.575 6255-6288 OpenGLRenderer jp.or.jaf.syg W Failed to set EGL_SWAP_BEHAVIOR on surface 0x7638696e4400, error=EGL_BAD_MATCH 2025-09-23 18:10:10.577 2140-2140 ContextImpl com.android.coreservice W Calling a method in the system process without a qualified user: android.app.ContextImpl.startService:1531 android.content.ContextWrapper.startService:664 android.content.ContextWrapper.startService:664 com.android.coreservice.CoreBroadcastReceiver.onReceive:70 android.app.ActivityThread.handleReceiver:3424 2025-09-23 18:10:10.632 1564-1571 System system_server W A resource failed to call close. 2025-09-23 18:10:10.633 1564-1571 chatty system_server I uid=1000(system) FinalizerDaemon identical 19 lines 2025-09-23 18:10:10.633 1564-1571 System system_server W A resource failed to call close. 2025-09-23 18:10:11.153 6255-6255 JafCommonLog jp.or.jaf.syg D [app] [clientID] [172.16.1.15] [main:(ID=2)] [JafNavDataManager:peek:148] JafNavDataManager: オブジェクト参照 ID=99be5cf6-223f-4339-ad71-2b462cb08562, Type=JAFRSHO07010Model 2025-09-23 18:10:11.160 6255-6255 chatty jp.or.jaf.syg I uid=10057(jp.or.jaf.syg) identical 1 line 2025-09-23 18:10:11.171 6255-6255 JafCommonLog jp.or.jaf.syg D [app] [clientID] [172.16.1.15] [main:(ID=2)] [JafNavDataManager:peek:148] JafNavDataManager: オブジェクト参照 ID=99be5cf6-223f-4339-ad71-2b462cb08562, Type=JAFRSHO07010Model 2025-09-23 18:10:12.925 1419-1464 EmuHWC2 and...graphics.composer@2.1-service D sent 324 syncs in 60s jafrsho07010画面可以进去 jafrsho07030日志: 2025-09-23 18:11:29.177 6517-6557 jp.or.jaf.syg jp.or.jaf.syg W Long monitor contention with owner arch_disk_io_1 (6555) at net.zetetic.database.sqlcipher.SQLiteDatabase net.zetetic.database.sqlcipher.SQLiteOpenHelper.getWritableDatabase()(SQLiteOpenHelper.java:277) waiters=2 in net.zetetic.database.sqlcipher.SQLiteDatabase net.zetetic.database.sqlcipher.SQLiteOpenHelper.getWritableDatabase() for 568ms 2025-09-23 18:11:29.177 6517-6557 SQLiteConnection jp.or.jaf.syg I Database keying operation returned:0 2025-09-23 18:11:29.357 6517-6557 sqlcipher jp.or.jaf.syg D ERROR CORE sqlcipher_page_cipher: hmac check failed for pgno=1 2025-09-23 18:11:29.357 6517-6557 sqlcipher jp.or.jaf.syg D ERROR CORE sqlite3Codec: error decrypting page 1 data: 1 2025-09-23 18:11:29.357 6517-6557 sqlcipher jp.or.jaf.syg D ERROR CORE sqlcipher_codec_ctx_set_error 1 2025-09-23 18:11:29.357 6517-6557 SQLiteLog jp.or.jaf.syg E (26) file is not a database in "SELECT COUNT(*) FROM sqlite_schema;" 2025-09-23 18:11:29.357 6517-6557 jp.or.jaf.syg jp.or.jaf.syg W JNI critical lock held for 179.624ms on Thread[24,tid=6557,Runnable,Thread*=0x76386d34dc00,peer=0x140010f8,"arch_disk_io_3"] 2025-09-23 18:11:29.357 6517-6557 SQLiteDatabase jp.or.jaf.syg E Failed to open database '/data/user/0/jp.or.jaf.syg/databases/vehicle_database'. net.zetetic.database.sqlcipher.SQLiteNotADatabaseException: file is not a database (code 26): , while compiling: SELECT COUNT(*) FROM sqlite_schema; at net.zetetic.database.sqlcipher.SQLiteConnection.nativePrepareStatement(Native Method) at net.zetetic.database.sqlcipher.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:973) at net.zetetic.database.sqlcipher.SQLiteConnection.executeForLong(SQLiteConnection.java:628) at net.zetetic.database.sqlcipher.SQLiteConnection.open(SQLiteConnection.java:240) at net.zetetic.database.sqlcipher.SQLiteConnection.open(SQLiteConnection.java:202) at net.zetetic.database.sqlcipher.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:474) at net.zetetic.database.sqlcipher.SQLiteConnectionPool.open(SQLiteConnectionPool.java:188) at net.zetetic.database.sqlcipher.SQLiteConnectionPool.open(SQLiteConnectionPool.java:180) at net.zetetic.database.sqlcipher.SQLiteDatabase.openInner(SQLiteDatabase.java:1028) at net.zetetic.database.sqlcipher.SQLiteDatabase.open(SQLiteDatabase.java:1013) at net.zetetic.database.sqlcipher.SQLiteDatabase.openDatabase(SQLiteDatabase.java:840) at net.zetetic.database.sqlcipher.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:359) at net.zetetic.database.sqlcipher.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:278) at net.zetetic.database.sqlcipher.SupportHelper.getWritableDatabase(SupportHelper.java:60) at androidx.room.RoomDatabase.inTransaction(RoomDatabase.kt:632) at androidx.room.RoomDatabase.assertNotSuspendingTransaction(RoomDatabase.kt:451) at androidx.room.RoomDatabase.query(RoomDatabase.kt:480) at androidx.room.util.DBUtil.query(DBUtil.kt:75) at jp.or.jaf.syg.data.local.dao.transaction.TShireiDataDao_Impl$28.call(TShireiDataDao_Impl.java:13605) at jp.or.jaf.syg.data.local.dao.transaction.TShireiDataDao_Impl$28.call(TShireiDataDao_Impl.java:13601) at androidx.room.CoroutinesRoom$Companion$execute$4$job$1.invokeSuspend(CoroutinesRoom.kt:87) at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:108) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:764) 2025-09-23 18:11:32.426 1431-1431 ldinit ldinit I type=1400 audit(0.0:2155): avc: denied { read } for name="partitions" dev="proc" ino=4026532050 scontext=u:r:ldinit:s0 tcontext=u:object_r:proc:s0 tclass=file permissive=1 2025-09-23 18:11:32.426 1431-1431 ldinit ldinit I type=1400 audit(0.0:2155): avc: denied { open } for path="/proc/partitions" dev="proc" ino=4026532050 scontext=u:r:ldinit:s0 tcontext=u:object_r:proc:s0 tclass=file permissive=1 2025-09-23 18:11:32.426 1431-1431 ldinit ldinit W type=1300 audit(0.0:2155): arch=c000003e syscall=257 success=yes exit=6 a0=ffffff9c a1=76391789f1b8 a2=0 a3=0 items=0 ppid=1 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=(none) ses=4294967295 exe="/system/bin/ldinit" subj=u:r:ldinit:s0 key=(null) 2025-09-23 18:11:32.426 1358-1358 auditd pid-1358 W type=1327 audit(0.0:2155): proctitle="/system/bin/ldinit" 2025-09-23 18:11:32.426 1358-1358 auditd pid-1358 W type=1320 audit(0.0:2155): jafrsho07030画面出现问题
09-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值