Flutter SQLite没有这样的专栏

时间:2019-08-29 16:06:18

标签: 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');
 }
}

1 个答案:

答案 0 :(得分:1)

您应该将参数(尤其是字符串)用于参数

代替:

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});