Flutter删除sqllite中的所有行

6yoyoihd  于 2023-05-23  发布在  Flutter
关注(0)|答案(2)|浏览(116)

需要删除SQLite中的所有行
这是我拥有数据库所有功能的文件

class DatabaseHelper {

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

  static final table = 'cart_table';

  // 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 ("
    "uId INTEGER PRIMARY KEY,"
        "id INTEGER,"
        "title TEXT,"
    "image TEXT,"
    "color TEXT,"
    "price TEXT,"
    "sizeselect TEXT"
    ")");

  }

  Future<int> insert(cart) async {
    print(cart.id);
    Database db = await instance.database;
    return await db.insert(table, cart.toJson());
  }

  Future<List<Map<String, dynamic>>> queryAllRows() async {
    Database db = await instance.database;
    return await db.query(table);
  }

  Future<int> queryRowCount() async {
    Database db = await instance.database;
    return Sqflite.firstIntValue(await db.rawQuery('SELECT COUNT(*) FROM $table'));
  }

  Future<int> delete(int id, columnId) async {
    print(columnId);
    print(id);
    Database db = await instance.database;
    return await db.delete(table, where: '$columnId = id');
  }

  deleteAll() async {
    Database db = await instance.database;
    return await db.rawDelete("Delete * from $table");
  }
}

我需要删除所有行。所以我就这样做了

final dbHelper = DatabaseHelper.instance;

 allRows = await dbHelper.queryAllRows();

显示错误Unhandled Exception: DatabaseException(near "*": syntax error (code 1 SQLITE_ERROR): , while compiling: Delete * from cart_table) sql 'Delete * from cart_table' args []}
我不明白为什么它会显示错误,因为不需要传递任何东西,它会显示错误。我需要的只是删除整个表

1qczuiv0

1qczuiv01#

尝试在不使用*的情况下调用删除操作:

delete from cart_table
1hdlvixo

1hdlvixo2#

不需要使用 *。只需像下面的代码一样调用

clearUserTable() async {
    Database db = await instance.database;
    return await db.rawDelete("DELETE FROM $tableName");
  }

相关问题