0

I'm trying to query the last 3 hours of entries from my sqflite database. Here's my current query:

Future<List<Map<String, dynamic>>> queryLastThreeHours() async {
    Database db = await instance.database;
    return await db.query(table, where: '$columnDate = ?', whereArgs: ['now', '-3 hours']);
  }

For more context, here's the complete code for the database_helper.dart:

import 'dart:io';

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';

class DatabaseHelper {

  static final _databaseName = "MyDatabase.db";
  static final _databaseVersion = 1;

  static final table = 'my_table';

  static final columnId = '_id';
  static final columnName = 'name';
  static final columnAge = 'age';
  static final columnColour = 'colour';
  static final columnDate = 'date';

  // make this a singleton class
  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  // only have a single app-wide reference to the database
  static Database _database;
  Future<Database> get database async {
    if (_database != null) return _database;
    // lazily instantiate the db the first time it is accessed
    _database = await _initDatabase();
    return _database;
  }

  // this opens the database (and creates it if it doesn't exist)
  _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path,
        version: _databaseVersion,
        onCreate: _onCreate);
  }

  // SQL code to create the database table
  Future _onCreate(Database db, int version) async {
    await db.execute('''
          CREATE TABLE $table (
            $columnId INTEGER PRIMARY KEY,
            $columnName TEXT NOT NULL,
            $columnAge INTEGER NOT NULL,
            $columnColour TEXT NOT NULL,
            $columnDate INTEGER NOT NULL
          )
          ''');
  }

  // Helper methods

  // Inserts a row in the database where each key in the Map is a column name
  // and the value is the column value. The return value is the id of the
  // inserted row.
  Future<int> insert(Map<String, dynamic> row) async {
    Database db = await instance.database;
    return await db.insert(table, row);
  }

  // All of the rows are returned as a list of maps, where each map is
  // a key-value list of columns.
  Future<List<Map<String, dynamic>>> queryAllRows() async {
    Database db = await instance.database;
    return await db.query(table);
  }

  // All of the methods (insert, query, update, delete) can also be done using
  // raw SQL commands. This method uses a raw query to give the row count.
  Future<int> queryRowCount() async {
    Database db = await instance.database;
    return Sqflite.firstIntValue(await db.rawQuery('SELECT COUNT(*) FROM $table'));
  }

  // We are assuming here that the id column in the map is set. The other
  // column values will be used to update the row.
  Future<int> update(Map<String, dynamic> row) async {
    Database db = await instance.database;
    int id = row[columnId];
    return await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);
  }

  // Deletes the row specified by the id. The number of affected rows is
  // returned. This should be 1 as long as the row exists.
  Future<int> delete(int id) async {
    Database db = await instance.database;
    return await db.delete(table, where: '$columnId = ?', whereArgs: [id]);
  }

  Future<List<Map<String, dynamic>>> queryOmnivore() async {
    Database db = await instance.database;
    return await db.query(table, where: '$columnColour = ?', whereArgs: ['Omnivore']);
  }

  Future<List<Map<String, dynamic>>> queryLastThreeHours() async {
    Database db = await instance.database;
    return await db.query(table, where: '$columnDate = ?', whereArgs: ['now', '-3 hours']);
  }

}

Any help would be greatly appreciated. I've tried to work it out using Sqlite SELECT * for Last 7 days and How to get Last 3 hours data from SQLite, but still haven't figured it out.

Thank you very much in advance!

Jason

Jason Lloyd
  • 378
  • 7
  • 23
  • `$columnDate INTEGER NOT NULL` so are you storing date as epoch? – Dev Feb 19 '20 at 07:23
  • a hint if you have one `?` in the `where` string you need exactly one value inside `whereArgs` array (of course this is NOT a solution for your problem but you have to make it at the beginning) – pskink Feb 19 '20 at 07:24
  • thank you for your response @pskink. I've just tried updating it this and still getting an error: Future>> queryLastThreeHours() async { Database db = await instance.database; return await db.query(table, where: '$columnDate = ??', whereArgs: ['now', '-3 hours']); } – Jason Lloyd Feb 19 '20 at 07:29
  • the error message is: E/flutter ( 5655): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: DatabaseException(near "?": syntax error (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM my_table WHERE date = ??) sql 'SELECT * FROM my_table WHERE date = ??' args [now, -3 hours]} – Jason Lloyd Feb 19 '20 at 07:30
  • thanks for your comment @Dev. I thought it was being stored as integer, but i'm still pretty new to coding so not entirely sure? – Jason Lloyd Feb 19 '20 at 07:33
  • what is the content stored in the field column if you can provide something on that or some dummy record that you inserted then it will be easy to know if it is epoch – Dev Feb 19 '20 at 10:28
  • I can run a query for finding a specific datetime, which works fine: `Future>> querySpecificDateTime() async { Database db = await instance.database; return await db.rawQuery('SELECT * FROM $table WHERE $columnDate = ?', ['2020-02-19T05:45:19.439229']);` Now I'm just trying to figure out how to get the query to return a list of all records that are less than 7 days old. Any thoughts? – Jason Lloyd Feb 20 '20 at 08:22
  • @Dev Hi Dev heres a dummy record: _id: 4, name: Bob, age: 23, colour: Red, date: 2020-02-19T05:45:19.439229 – Jason Lloyd Feb 20 '20 at 09:18

0 Answers0