flutter 并非所有列都添加到sqflite的rawInsert方法中

izkcnapc  于 2023-03-24  发布在  Flutter
关注(0)|答案(1)|浏览(123)

我试图添加一行到我的“练习”表为我的健身房_跟踪器应用程序,奇怪的是,每当我添加练习不是所有的项目都插入,我是新的sqflite所以可能有一些错误在我的代码,请告诉我,如果这看起来正确:这是我的exercise create方法:

Future<Database> initialdatabase2() async {
    String databasepath = await getDatabasesPath();
    var path = join(databasepath, "exercises.db");
    Database mydb = await openDatabase(path,
        onCreate: _oncreate2, version: 1, onUpgrade: _onupgrade);
    return mydb;
  }

//exercise db
  _oncreate2(Database db2, int version) async {
    await db2.execute('''
CREATE TABLE "exercises" 
(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT , workoutname Text , exercisename Text , sets INTEGER , reps INTEGER , weight REAL
) 
    ''');

这是我的插入方法:

insertData2(String sql) async {
    Database? db = await get2();
    int response = await db!.rawInsert(sql);
    return response;
  }

这是我在我的cubit中使用它的地方(我使用cubit作为我的状态管理):

void addexercise(
      {required String name,
      required String workoutname,
      required int reps,
      required int sets,
      required double weight}) async {
    print(name);
    print(workoutname);
    print(reps);
    print(sets);
    print(weight);
    emit(ExercisesListLoadingState());
    await casheHelper
        .insertData2(
            "INSERT INTO 'exercises' (workoutname ,exercisename , sets ,reps ,weight) VALUES ('$workoutname','$name',$sets ,$reps ,$weight )")
        .then((value) {
      exercisesname = [];
      loadexercises();
      print("exercise added");
      emit(ExercisesListAddSuccessState());
    });
  }

请注意,当我在我的cubit方法中打印数据时,我拥有所有数据,但每当我从表中调用它们时,只有其中两个(workoutname和weight)为null。

uxh89sit

uxh89sit1#

也许这不是原因,但你应该首先使用参数,而不是把参数放在sql语句中,也就是说,而不是

rawInsert("INSERT INTO 'exercises' (workoutname ,exercisename , sets ,reps ,weight) 
  VALUES ('$workoutname','$name',$sets ,$reps ,$weight )");

试试这样的:

rawInsert("INSERT INTO 'exercises' (workoutname ,exercisename , sets ,reps ,weight) 
  VALUES (?, ?, ?, ?, ?)", [workoutname,name, sets, reps, weight]);

更多信息:https://github.com/tekartik/sqflite/blob/master/sqflite/doc/sql.md#parameters

相关问题