database - Flutter SQLite 没有这样的列

标签 database sqlite flutter dart sqflite

我正在使用 Flutter SQFlite 插件开发一个使用 SQLite 数据库的 Flutter 应用程序。 问题是,当我尝试插入一些测试数据时,应用程序会在控制台中打印以下内容:

Unhandled Exception: DatabaseException(no such column: dummy_value (code 1): , while compiling: INSERT INTO DemoTable (name) VALUES(dummy_value)) sql 'INSERT INTO DemoTable (name) VALUES(dummy_value)' args []}

据我从日志中了解到,问题出在列 'dummy_value' 但真正的问题在于,我的数据库有列 'id' 和 'name' 而 'dummy_value' 是发送到的值插入“名称”列。

以下是我创建数据库的代码:

class DatabaseCreator {
static const table = 'DemoTable';
static const id = 'id';
static const name = 'name';
static Database db;

initDatabase() async {
Directory documentsDirectory = await 
getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, 'Demo.db');
db = await openDatabase(path, version: 1, onCreate: _onCreate);
return db;
}

Future<void> _onCreate(Database db, int version) async {
await db.execute('''
      CREATE TABLE $table (
        $id INTEGER PRIMARY KEY AUTOINCREMENT,
        $name TEXT
      )
      ''');
  }
}

下面是将数据插入数据库的代码:

class DBOP {
static insertName(String name) async {
Database db = await DatabaseCreator().initDatabase();
final result = await db.rawInsert(
    'INSERT INTO ${DatabaseCreator.table} (${DatabaseCreator.name}) 
VALUES($name)');
print(result);
 }
}

最后,以下是我的有状态小部件:

class StFull extends StatefulWidget {
@override
_StFullState createState() => _StFullState();
}

class _StFullState extends State<StFull> {
@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text('DB Demo'),
  ),
  body: Container(
    child: RaisedButton(
      onPressed: _insertData,
      child: Text('INSERT DATA'),
    ),
    ),
  );
}

_insertData() {
DBOP.insertName('dummy_value');
 }
}

最佳答案

你应该为值(尤其是字符串)使用参数

代替:

await db.rawInsert(
    'INSERT INTO ${DatabaseCreator.table} (${DatabaseCreator.name}) VALUES($name)');

做类似的事情:

await db.rawInsert(
    'INSERT INTO ${DatabaseCreator.table} (${DatabaseCreator.name}) VALUES(?)', [name]);

或者更简单:

await db.insert(DatabaseCreator.table, <String, dynamic>{DatabaseCreator.name: name});

关于database - Flutter SQLite 没有这样的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57714024/

相关文章:

database - 如果有两种用户怎么办

java - 同一 JDBC 事务中的 Web 服务调用导致数据库锁定超时

sql - 确定按其他分组时sql表是否包含特定条目

android - 如何在 android 中使用 SQLitePlugin Cordova 填充数据库?

flutter - 如果您的项目有 dart html 导入,如何在模拟器上运行 flutter

java - Web 应用程序如何使用服务器发送的事件获取数据库更新并将更新传播到 Web 客户端?

c# - 谁可以访问 MVVM 模式中的数据库

.net - 如何连接到内存中的共享缓存数据库?

android - 更改 CustomPaint 的颜色会更改所有先前的点

android - 没有 Firebase 的 flutter 中的 OTP 验证