对sqlite求和

时间:2017-12-15 18:22:25

标签: android sqlite android-sqlite

我试图在SQLiteDB android中找到一列的总和。

这是我的搜索查询:

12-15 23:38:51.528 23462-23462/inc.circl.expy E/SQLiteLog: (1) near "(": syntax error
12-15 23:38:51.532 23462-23462/inc.circl.expy E/AndroidRuntime: FATAL EXCEPTION: main
    Process: inc.circl.expy, PID: 23462
    java.lang.RuntimeException: Unable to start activity ComponentInfo{inc.circl.expy/inc.circl.expy.HomeActivity}: android.database.sqlite.SQLiteException: near "(": syntax error (code 1): , while compiling: SELECT cat sum(cost) FROM tab_nam group by cat
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2521)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2595)
        at android.app.ActivityThread.access$800(ActivityThread.java:178)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
        at android.os.Handler.dispatchMessage(Handler.java:111)
        at android.os.Looper.loop(Looper.java:194)
        at android.app.ActivityThread.main(ActivityThread.java:5631)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
     Caused by: android.database.sqlite.SQLiteException: near "(": syntax error (code 1): , while compiling: SELECT cat sum(cost) FROM tab_nam group by cat
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:898)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:509)

但上面的执行查询会抛出错误:

catch (NoSuchMethodException e){  
  e.printStackTrace();  
}

我搜索过这个问题......

Android get sum of database column

how to get the sum of all numbers in a column in a sqlite databse, android

但我仍然被卡住了。

2 个答案:

答案 0 :(得分:4)

您忘记了逗号SELECT cat, SUM(cost) FROM " + TAB_NAM + " group by cat

此外,为了最佳实践,您不应该将字符串连接到SQL查询。它可以让您了解SQL注入式攻击。

答案 1 :(得分:1)

在每列之间添加逗号:

String selectQuery = "SELECT cat , SUM(cost) FROM " + TAB_NAM + " group by cat";