如何在Flutter中对SQLite数据库中的多个表执行CRUD操作?

时间:2019-11-26 03:02:25

标签: database sqlite flutter dart crud

我正在构建一个资金预算应用程序,用户可以在其中将月薪分配到5个领域:食物,社交,教育,旅行,储蓄。我有一个注册并登录屏幕。这是在Flutter / dart中,我正在使用sqlite。

要存储的一些数据: id,用户名,密码,电子邮件,monthly_salary,food_initial,food_final,social_initial,social_final,education_initial,education_final,travel_initial,travel_final,Savingsinitial,Savingsfinal

“初始” 是指用户将根据月薪的划分为自己输入的值。 (即,每月5000美元/ 5个容器=每个容器1000个。但是,用户可以将此值1000作为其初始预算金额进行编辑)。 “最终” 是指用户在该容器中剩余的钱(假设他们没有越过)。

初始 最终 值在月底重置。但是,我想保存他们前一个月的最终值,以便用户可以看到他们所做工作的积压。

最初,我的数据库有2个表。一个用于 USER_DATA ,另一个用于 BUDGETS 表。但是,在努力弄清楚如何对两个表进行CRUD操作之后,我决定将它们全部合并到一个表中。但是,在遇到一张桌子的麻烦之后,我想移回多张桌子。我现在很困惑:

         1. How to use CRUD operations when having more than one table on DB? 
         2. Do I have to build a new model class in order to have more than one table?
         3. How to save some of the user's data on database, but have to wait for the rest of the information to come in (later on while they're using the app)? 

为模型类构造构造函数,然后在UI中引用模型类时,它要求我引入我拥有的所有参数,但我还没有准备好所有这些值。用户仍然需要注册才能输入薪水等。我是否必须使用Future类来克服这一障碍?

我看过很多关于其他视频的视频,这些视频都是在sqlite和Flutter上建立数据库的,但是他们通常都做一个简单的待办事项列表应用,在那里他们需要填写表的每一列,而我还没有尚未看到其中包括几张桌子的桌子。 (即列:ID,说明,优先级,日期)

-

我认为现在在UI方面有很好的基础,并且使用TextFormFields访问信息,但是连接数据库/正确创建它会使我感到困惑。

我也正在考虑在继续操作之前将数据库写入.sql文件。我一直在通过教程(作为背景知识)自学Flutter。

我知道这有点长,到处都是,但是对于在Flutter中拥有sqlite环境经验的人,我将不胜感激,请帮助我了解如何正确执行此操作。

谢谢。另外,如果需要更多说明/代码,请告诉我。

模型类:

import 'dart:core';

class UserData {
  //user table
  int _userid;
  String _username;
  String _password;
  String _email;
  String _first_name;
  String _last_name;
  String _date;

   int _month_id;
  bool _subtract; //did the user subtract money from their funds? true/false
  double _month_salary;
  String _log_details;

  /////////////budget table
  double _edu_budget_initial;
  double _edu_budget_final;
  double _travel_budget_initial;
  double _travel_budget_final;
  double _living_budget_initial;
  double _living_budget_final;
  double _savings_budget_initial;
  double _savings_budget_final;
  double _social_budget_initial;
  double _social_budget_final;






  // using [___] around your user's data entry makes it optional in the table
  // otherwise, these are all required fields

  UserData(
      this._username,
      this._email,
      this._first_name,
      this._last_name,
      this._password,
      this._date,
      this._month_id,
      this._subtract,
      this._month_salary,
      this._log_details,
      this._edu_budget_final,
      this._edu_budget_initial,
      this._living_budget_final,
      this._living_budget_initial,
      this._savings_budget_final,
      this._savings_budget_initial,
      this._social_budget_final,
      this._social_budget_initial,
      this._travel_budget_final,
      this._travel_budget_initial);

//created a Named Constructor for the ability to create multiple constructors in one class
  UserData.withId(
      this._userid,
      this._username,
      this._password,
      this._first_name,
      this._last_name,
      this._email,
      this._date,
      this._month_id,
      this._subtract,
      this._month_salary,
      this._log_details,
      this._edu_budget_final,
      this._edu_budget_initial,
      this._living_budget_final,
      this._living_budget_initial,
      this._savings_budget_final,
      this._savings_budget_initial,
      this._social_budget_final,
      this._social_budget_initial,
      this._travel_budget_final,
      this._travel_budget_initial);


//UserData.budgetTable(this.date, this.month_id, this.log_details, this.edu_budget_final, this.edu_budget_initial, this.living_budget_final, this.living_budget_initial,
 //this.month_salary, this.savings_budget_final, this.savings_budget_initial, this.social_budget_final,
//this.social_budget_initial, this.travel_budget_final, this.travel_budget_initial);


//getters:

//userdata table
  int get userid => _userid;
  String get username => _username;
  String get password => _password;
  String get email => _email;
  String get firstname => _first_name;
  String get lastname => _last_name;
  String get date => _date;




//budget table
  int get month_id => _month_id;
  bool get subtract => _subtract;
  double get month_salary => _month_salary; 

  String get log_details => _log_details;

  double get living_budget_initial => _living_budget_initial;
  double get living_budget_final => _living_budget_final;
  double get social_budget_initial => _social_budget_initial;
  double get social_budget_final => _social_budget_final;
  double get edu_budget_initial => _edu_budget_initial;
  double get edu_budget_final => _edu_budget_final;
  double get travel_budget_initial => _travel_budget_initial;
  double get travel_budget_final => _travel_budget_final;
  double get savings_budget_initial => _savings_budget_initial;
  double get savings_budget_final => _savings_budget_final;

//setters:

/*
set userid(int newUserID) {
  //adding condition before storing what user put in
  if (newUserID <= 12) {
    this._userid = newUserID; 
  }

}
*/

  set username(String newUsername) {
    if (newUsername.length <= 30) {
      this._username = newUsername;
    }
  }

  set password(String newPassword) {
    if (newPassword.length <= 30) 
      this._password = newPassword;
  }

  set email(String newEmail) {
    if (newEmail.length <= 50) 
      this._email = newEmail;
  }

  set first_name(String newFirstName) {
    if (newFirstName.length <= 30) 
      this._first_name = newFirstName;
  }

  set last_name(String newLastName) {
    if (newLastName.length <= 30) 
     this._last_name = newLastName;
  }

  set month_id(int newMonthId) {
    if (newMonthId <= 12) {
      this._month_id = newMonthId;
    }
  }

  set month_salary(double newMonthSalary) {
    this._month_salary = newMonthSalary; 
  }

  set date(String newDate) {
    this._date = newDate;
  }

  set log_details(String newLogDetails) {
    if (newLogDetails.length <= 255) 
    this._log_details = newLogDetails;
  }

  set subtract(bool newSubtract) {
    this._subtract = newSubtract;
  }

  set living_budget_initial(double newLBI) {
    if (newLBI <= 10) this._living_budget_initial = newLBI;
  }

  set living_budget_final(double newLBF) {
    if (newLBF <= 10) this._living_budget_final = newLBF;
  }

  set social_budget_initial(double newSOBI) {
    if (newSOBI <= 10) this._social_budget_initial = newSOBI;
  }

  set social_budget_final(double newSOBF) {
    if (newSOBF <= 10) this._social_budget_final = newSOBF;
  }

  set edu_budget_initial(double newEBI) {
    if (newEBI <= 10) this._edu_budget_initial = newEBI;
  }

  set edu_budget_final(double newEBF) {
    if (newEBF <= 10) this._edu_budget_final = newEBF;
  }

  set travel_budget_initial(double newTBI) {
    if (newTBI <= 10) this._travel_budget_initial = newTBI;
  }

  set travel_budget_final(double newTBF) {
    if (newTBF <= 10) this._travel_budget_final = newTBF;
  }

  set savings_budget_initial(double newSBI) {
    if (newSBI <= 10) this._savings_budget_initial = newSBI;
  }

  set savings_budget_final(double newSBF) {
    if (newSBF <= 10) this._savings_budget_final = newSBF;
  }

// converting object into Map objects
  Map<String, dynamic> toMap() {
    var map = Map<String, dynamic>();
    var userid;
    if (userid != null) {
      map['userid'] = _userid;
    }
    map['userid'] = _userid;
    map['username'] = _username;
    map['password'] = _password;
    map['email'] = _email;
    map['first_name'] = _first_name;
    map['last_name'] = _last_name;
//
    map['month_id'] = _month_id;
    map['month_salary'] = _month_salary; 
    map['date'] = _date;
    map['log_details'] = _log_details;
    map['subtract'] = _subtract;
    map['living_budget_initial'] = _living_budget_initial;
    map['living_budget_final'] = _living_budget_final;
    map['social_budget_initial'] = _social_budget_initial;
    map['social_budget_final'] = _social_budget_final;
    map['edu_budget_initial'] = _edu_budget_initial;
    map['edu_budget_final'] = _edu_budget_final;
    map['travel_budget_initial'] = _travel_budget_initial;
    map['travel_budget_final'] = _travel_budget_final;
    map['savings_budget_initial'] = _savings_budget_initial;
    map['savings_budget_final'] = _savings_budget_final;

    return map;
  }

//converts map objects into objects
  UserData.fromMapObject(Map<String, dynamic> map) {
    this._userid = map['userid'];
    this._username = map['username'];
    this._password = map['password'];
    this._email = map['email'];
    this.first_name = map['first_name'];
    this.last_name = map['last_name'];
//
    this._month_id = map['month_id'];
    this._month_salary = map['month_salary'];
    this._date = map['date'];
    this._log_details = map['log_details'];
    this._subtract = map['subtract'];
    this._living_budget_initial = map['living_budget_initial'];
    this._living_budget_final = map['living_budget_final'];
    this._social_budget_initial = map['social_budget_initial'];
    this._social_budget_final = map['social_budget_final'];
    this._edu_budget_initial = map['edu_budget_initial'];
    this._edu_budget_final = map['edu_budget_final'];
    this._travel_budget_initial = map['travel_budget_initial'];
    this._travel_budget_final = map['travel_budget_final'];
    this._savings_budget_initial = map['savings_budget_initial'];
    this._savings_budget_final = map['savings_budget_final'];
  }
}


数据库帮助程序类:

import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:jewell_1/user_data.dart';

class DbHelper {
// Create a private instance of the class
  static final DbHelper _dbhelper = new DbHelper._internal();
  String DB_name = "user_data.db";
  static final int DATABASE_VERSION = 2;

  String userDataTable = 'user_data_table';

  String colUserId = 'userid';
  String colUsername = 'username';
  String colPassword = 'password';
  String colEmail = 'email';
  String colFirstName = 'first_name';
  String colLastName = 'last_name';
  String colDate = 'date';

  String colMonthId = 'month_id';
  String colSubtract = 'subtract';
  String colMonthSalary = 'month_salary';

  String colLogDetails = 'log_details';

  String colLBI = 'living_budget_initial';
  String colLBF = 'living_budget_final';
  String colSOBI = 'social_budget_initial';
  String colSOBF = 'social_budget_final';
  String colEBI = 'edu_budget_initial';
  String colEBF = 'edu_budget_final';
  String colTBI = 'travel_budget_initial';
  String colTBF = 'travel_budget_final';
  String colSBI = 'savings_budget_initial';
  String colSBF = 'savings_budget_final';

// Create an empty private named constructor
  DbHelper._internal();

// Use the factory to always return the same instance
  factory DbHelper() {
    return _dbhelper;
  }

   static Database _db;

  Future<Database> get db async {
    if (_db == null) {
      _db = await initializeDb();
    }
    return _db;
  }

  Future<Database> initializeDb() async {
    Directory dir = await getApplicationDocumentsDirectory();
    String path = dir.path + "todos.db";
    var dbTodos = await openDatabase(path, version: DATABASE_VERSION, onCreate: _createDb);
    return dbTodos;
  }

  void _createDb(Database db, int newVersion) async {
    await db.execute(
        "CREATE TABLE $userDataTable($colUserId INETEGER PRIMARY KEY, $colUsername TEXT," +
            "$colPassword TEXT, $colEmail TEXT, $colFirstName TEXT,"
            "$colLastName TEXT, $colDate TEXT, $colMonthId INTEGER,"
            " $colSubtract BOOLEAN, $colMonthSalary DOUBLE, $colLogDetails TEXT,"
            " $colEBI DOUBLE, $colEBF DOUBLE, $colTBI DOUBLE, $colTBF DOUBLE, "
            " $colLBI DOUBLE, $colLBF DOUBLE, $colSBI DOUBLE, $colSBF DOUBLE,"
            " $colSOBI DOUBLE, $colSOBF DOUBLE)");

  }

Future<int> insertData(UserData data) async {
    Database db = await this.db;
    var result = await db.insert(userDataTable, data.toMap());
    return result;
  }

  Future<List> getDatas() async {
    Database db = await this.db;
    var result =
        await db.rawQuery("SELECT * FROM $userDataTable order by $colUserId ASC");
    return result;
  }

  Future<int> getCount() async {
    Database db = await this.db;
    var result = Sqflite.firstIntValue(
        await db.rawQuery("SELECT COUNT (*) FROM $userDataTable"));
    return result;
  }

  Future<int> updateData(UserData data) async {
    var db = await this.db;
    var result = await db
        .update(userDataTable, data.toMap(), where: "$colUserId=?", whereArgs: [data.userid]);
    return result;
  }

  Future<int> deleteData(int id) async {
    int result;
    var db = await this.db;
    result = await db.rawDelete("DELETE FROM $userDataTable WHERE $colUserId=$id");
    return result;

}

}

更具体地说,我对不编写新表的查询感到困惑,而是在这一点上:

 var result = await db.insert(userDataTable, data.toMap());
 return result;

结果只包含我的userDataTable,如果我创建另一个表,那我应该添加另一个var结果吗?我试图拥有:

 var result2 = await db.insert(budgetsTable, data.toMap());

这似乎是错误的。另外,我也不知道如何返回两个结果。 那是/当我开始清理使用Flutter在sqlite上使用多个桌子进行CRUD操作的人们的互联网的地方。

0 个答案:

没有答案
相关问题