在 SQLite FLutter 数据库中创建一个 DATETIME 列? [英] Create a DATETIME column in SQLite FLutter database?

查看:78
本文介绍了在 SQLite FLutter 数据库中创建一个 DATETIME 列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个带有一些列的 TABLE 并且一切正常,直到我尝试插入一个新的 DATETIME 列:

I create a TABLE with some columns and everything's ok until I tried to insert a new DATETIME column:

_onCreate(Database db, int version) async {
await db.
execute("CREATE TABLE $TABLE ($ID INTEGER PRIMARY KEY, $NAME TEXT, $COLOUR 
TEXT, $BREED TEXT, $BIRTH DATETIME)");
}

我要存储的模型类是:

class Pet {
 int id;
 String name;
 DateTime birth;
 String breed;
 String colour;

 Pet({this.id, this.name, this.birth, this.colour, this.breed});
 }

在控制器中,我尝试存储一个 Pet 的新实例,实例化一个新变量 DateTime _date = new DateTime.now(); 并将所有内容保存在

In the controller, I tried to store a new instance of Pet, instantiating a new variable DateTime _date = new DateTime.now(); and saving all in

Pet newPet = Pet(
      id: null,
      name: _name,
      colour: _colour,
      breed: _breed,
      birth: _date
  );

但是当我插入数据库时​​,我收到:

But when I insert in the database I receive:

未处理的异常:无效参数:DateTime"的实例

Unhandled Exception: Invalid argument: Instance of 'DateTime'

推荐答案

可能你直接传递了 DateTime 对象.

Probably you are passing DateTime object directly.

使用类方法,例如:

https://api.dart.dev/stable/2.9.3/dart-core/DateTime/millisecondsSinceEpoch.html

https://api.dartlang.org/stable/2.4.0/dart-core/DateTime/toIso8601String.html

您需要传递 Stringint 而不是对象.原因是,您必须使用支持的 SQLite 数据类型来存储在 SQLite 表中,请在此处找到支持的数据类型列表 https://www.sqlite.org/datatype3.html

You need to pass String or int instead of an Object. The reason being, you must use supported SQLite data types to store in a SQLite table, find a list of supported data types here https://www.sqlite.org/datatype3.html

还结帐:

https://pub.dev/packages/sqflite

DateTime 不是受支持的 SQLite 类型.我个人将它们存储为 int (millisSinceEpoch) 或 string (iso8601)

DateTime is not a supported SQLite type. Personally I store them as int (millisSinceEpoch) or string (iso8601)

再次检索您的 DateTime 对象:

To retrieve your DateTime object again:

从整数:

DateTime.fromMillisecondsSinceEpoch(yourValue);

来自字符串:

DateTime.parse(yourValue);

或更好的方法:

DateTime.tryParse(yourValue);

这篇关于在 SQLite FLutter 数据库中创建一个 DATETIME 列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆