【问题标题】:DatabaseException(UNIQUE constraint failed: prop_mst.prop_id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY))DatabaseException(唯一约束失败:prop_mst.prop_id(代码 1555 SQLITE_CONSTRAINT_PRIMARYKEY))
【发布时间】:2019-11-20 13:43:32
【问题描述】:

我正在使用 DBHelper 类,并且在我的其他类之一中调用 getter,以便如果 DB 为空,它会对其进行初始化。 在另一种方法中,我将从休息端点返回的数据插入数据库并获得上述异常。我想也许因为记录已经存在,我得到了例外。在那种情况下,我想了解数据库何时创建以及生命周期。大多数网络上关于 sqflite 的文章都是基于 CRUD 操作的。

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



Future<Database> initializeDb() async{
    Directory dir = await path_pro.getApplicationDocumentsDirectory();
    String path = dir.path + 'csr';
    var dbCsr = await openDatabase(path, version: 1, onCreate: _createDb);
    return dbCsr;
  }
  void _createDb(Database db, int newVersion) async{
    await db.execute(
      "CREATE TABLE $tblName($colPropId INTEGER PRIMARY KEY, $colCityName TEXT, $colPropName TEXT, $colPropAddr TEXT)"
    );
  }
  Future<int> insertProp(Map<String, dynamic> map) async{
    Database db = await this.db;
    var result = await db.insert(tblName, map);
    return result;
  }

在我的其他课程中,我将其称为如下:

DBHelper().db

DBHelper().insertProp(element[i]);

谢谢

【问题讨论】:

    标签: flutter sqflite


    【解决方案1】:

    在插入方法中的 DBHelper 类中,我首先使用选择查询来检查是否有条目...如果存在我更新它,如果没有我插入到数据库中。

    Future<int> insertProp(Map<String, dynamic> map) async{
        var result;
        Database db = await this.db;
        var count = Sqflite.firstIntValue(await db.rawQuery('SELECT COUNT(*) from 
                    $tblName WHERE $colPropId = ? ', [map['prop_id']]));
        if(count == 0){
          result = await db.insert(tblName, map);
        }else{
           await db.update(tblName, map, where: '$colPropId = ?', whereArgs: 
          [map['prop_id']]);
        }
        return result;
      }
    

    谢谢大家

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-20
      • 2019-12-18
      • 2019-04-28
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多