有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在安卓的SQLite数据库中运行查询?

在我的SQLite数据库管理器中,我可以查询:

SELECT SUM(odometer) as odometer FROM tripmileagetable where date like '2012-07%';

这个查询返回2012年7月名为“tripmileagetable”的表中里程表列的总和,但我想在安卓查询中编写这段代码

但我不知道如何在数据库中建立这个查询。query()方法,有人能帮忙吗


共 (5) 个答案

  1. # 1 楼答案

    这取决于你计划如何在Android中访问数据库。你可以尝试以下方法:

    SQLiteDatabase db = this.getWritableDatabase();
    String selectQuery = "select sum(odometer) as odometer from tripmileagetable where date like '2012-07%'";
    Cursor cursor = db.rawQuery(selectQuery, null);
    

    如果您使用的是SQLiteOpenHelper类,则可以使用上述方法

    如果您自己创建了数据库文件,可以执行以下操作:

    SQLiteDatabase db = SQLiteDatabase.openDatabase("/data/data/com.package.name/databases/dbname.db", null, SQLiteDatabase.OPEN_READWRITE);
    String selectQuery = "select sum(odometer) as odometer from tripmileagetable where date like '2012-07%'";
    Cursor cursor = db.rawQuery(selectQuery, null);
    

    对SQLiteDatase、游标和SQLiteOpenHelper进行一些研究

    此示例可能会帮助您:

    https://github.com/nraboy/Spyfi/blob/master/Android/src/com/nraboy/spyfi/DataSource.java

  2. # 2 楼答案

    您可以使用rawQuery方法:

    Cursor c = database.rawQuery("SELECT SUM(odometer) as odometer FROM tripmileagetable where date like '2012-07%'", null);
    
  3. # 3 楼答案

    final Cursor cursor = db.rawQuery("SELECT SUM(odometer) as odometer FROM tripmileagetable where date like '2012-07%';", null);
    int sum = 0;
    if (cursor != null) {
        try {
            if (cursor.moveToFirst()) {
                sum = cursor.getInt(0);
            }
        } finally {
            cursor.close();
        }
    }
    
  4. # 4 楼答案

    您的字段不是在表数据库上创建的,请检查表上的字段。因为我在自己身上看到了这个问题。我使用SQLite Administrator查看我的数据库

    或者,如果没有,请查看创建数据库的源代码。确保你的源代码是真实的,然后你可以在文件浏览器上删除你的旧数据库(我是说使用eclipse)。您可以使用新数据库再次运行

  5. # 5 楼答案

    Android完全支持SQLite DBs。你在应用程序内部创建的所有数据库都可以从应用程序的所有类访问(而不是从应用程序外部!)

    首先,您应该创建一个扩展SQLiteOpenHelper的Java类。在这里,您必须重写onCreate()onUpdate()方法。可以假设,在创建数据库时调用第一个,而在修改数据库时调用后一个

    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.content.Context;
    import android.database.Cursor;
    import android.content.ContentValues;
    
    
    /**
     * Class DatabaseHelper.
     */
    public class DatabaseHelper extends SQLiteOpenHelper {
        //Database parameters:
        private static final String DATABASE_NAME = "dbname";  // the name of the DB!
        private static final int DATABASE_VERSION = 2;
        private static final String DATABASE_TABLE_NAME = "tripmileagetable";  // the name of the table!
    
        //Table attributes:
        private static final String DATABASE_TABLE_ATTR_ID = "id";  // attr1
        private static final String DATABASE_TABLE_ATTR_ODOMETER = "odometer";  // attr2
        private static final String DATABASE_TABLE_ATTR_DATE = "date";  // attr3
    
    
        /**
         * Class constructor.
         *
         * @param context  the context.
         */
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            String create = "CREATE TABLE " + DATABASE_TABLE_NAME + " (" +
                            DATABASE_TABLE_ATTR_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                            DATABASE_TABLE_ATTR_ODOMETER + " INTEGER, " +
                            DATABASE_TABLE_ATTR_DATE + " TEXT);";
    
            db.execSQL( create );
        }
    
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_NAME);
            onCreate(db);
        }
    }
    

    现在,在新的Java类中,您可以创建自定义方法来查询数据库

    要写入数据库,应该使用getWritableDatabase(),而要读取数据库,应该使用getReadableDatabase()。它们都返回一个SQLiteDatabase对象,并最终抛出一个SQLiteException。 特别是,要查询数据库,有两种SQLiteDatabase方法可用:rawQueryquery(都返回游标对象)

    /**
     * Get the sum of the odometer of a particular month and year.
     *
     * @param year  the year.
     * @param month  the month.
     * @return the sum of the odometer of the year and the month.
     */
    public int sumOdometer(Integer year, Integer month) {
        //Date composition:
        String date = year.toString() + "-" + month.toString() + "%";
    
        //SQL query:
        String query = "SELECT SUM(" + DATABASE_TABLE_ATTR_ODOMETER + ") AS " + DATABASE_TABLE_ATTR_ODOMETER + 
                       " FROM " + DATABASE_TABLE_NAME +
                       " WHERE " + DATABASE_TABLE_ATTR_DATE + "LIKE ?";
    
        //Execute the SQL query:
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery(query, new String [] {date});
    
        int sum = 0;
        if( cursor.moveToFirst() ) {  // moves the cursor to the first row in the result set...
            sum = cursor.getInt( cursor.getColumnIndex(DATABASE_TABLE_ATTR_ODOMETER) );
        }
    
        //Close the Cursor:
        cursor.close();
    
        return sum;
    }
    

    请注意,SQLite会自动在参数(?)周围加上单引号(')

    你可以在这里找到一个很好的教程:http://www.codeproject.com/Articles/119293/Using-SQLite-Database-with-Android