如何在SQlite Android中使用选择查询

时间:2016-09-09 14:16:50

标签: android sqlite android-sqlite

我的“我的应用程序”中有一个数据库,我想根据当前日期从数据库中检索数据..我曾经使用过这个查询,但是当我点击后退按钮时,listView中没有显示任何内容

从BluetoothDevice中选择*,其中Date = current_date

public class UserDbHelper extends SQLiteOpenHelper {
public static final String DATABASENAME = "DATABASENAME2";
public static final int DB_VERSION = 1;


public UserDbHelper(Context context)
{
    super(context,DATABASENAME,null,DB_VERSION);


}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS BluetoothDevice ( Device VARCHAR , Address VARCHAR , Date VARCHAR);");

}
public List<BluetoothDevice>  getItemFromDatabase(SQLiteDatabase sqLiteDatabase) {
    List<BluetoothDevice> result = new ArrayList<>();
    // query database elements
    Cursor c = sqLiteDatabase.rawQuery("Select * from BluetoothDevice where Date = current_date;", null);

    while (c.moveToNext()) {
        Date date = new Date();
        date.setTime(Long.valueOf(c.getString(c.getColumnIndex("Date"))));
        result.add(
                new BluetoothDevice(
                        c.getString(c.getColumnIndex("Device")),
                        c.getString(c.getColumnIndex("Address")),
                        date

                )
        );
    }
    c.close();
    return result;
}

public void store(List<BluetoothDevice> data,SQLiteDatabase sqLiteDatabase) {
    for (BluetoothDevice value : data) {
        String s = String.valueOf(new Date().getTime());
        //insert in database
        sqLiteDatabase.execSQL("INSERT INTO  BluetoothDevice VALUES(?,?,?,?);", new String[]{value.name, value.address, s});

    }
}


@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}
}

1 个答案:

答案 0 :(得分:1)

您肯定需要将创建的表放入onUpgrade方法。

//Checks wether the old table has to be removed
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
    db.execSQL("DROP TABLE BluetoothDevice");
    onCreate(db);
}

此外,您需要在数据库中进行的每项更改中增加DB_VERSION