Sqlite没有使用默认值

时间:2018-02-24 00:27:03

标签: python sqlite

使用时:

import datetime
import sqlite3

db = sqlite3.connect('mydb.sqlite', detect_types=sqlite3.PARSE_DECLTYPES)
c = db.cursor()
db.text_factory = str

c.execute('create table if not exists mytable (date timestamp, title str, \
    custom str, x float, y float, z char default null, \
    postdate timestamp default null, id integer primary key autoincrement, \
    url text default null)')
c.execute('insert into mytable values(?, ?, ?, ?, ?)', \
    (datetime.datetime(2018,4,23,23,00), 'Test', 'Test2', 2.1, 11.1))

我有:

  

sqlite3.OperationalError:table mytable有9列,但提供了5个值

为什么SQlite在考虑填充新行时不采用默认值(在创建表格时指定)?

(另外,当我重新开始几年前写的一个项目时,我在sqlite3 doc中找不到数据类型strchar,它是否仍然相关?)

3 个答案:

答案 0 :(得分:3)

因为您说要通过不指定特定列来插入所有列。

更改li { display:inline-block; max-width: 100%; word-wrap:break-word; }

'insert into mytable values(?, ?, ?, ?, ?)'

几乎可以指定列类型的任何值,该值将遵循一组规则并转换为TEXT,INTEGER,REAL,NUMERIC或BLOB。但是,您可以在任何列中存储任何类型的值。

  • STR将解析为NUMERIC,
  • TIMESTAMP将解析为NUMERIC,
  • FLOAT将解析为REAL,
  • CHAR to TEXT。

阅读Datatypes In SQLite或者查看How flexible/restricive are SQLite column types?

答案 1 :(得分:2)

如果您只为某些列提供值,则需要指定哪些列。否则引擎将不知道放在哪里。这条线需要改变:

c.execute('insert into mytable values(?, ?, ?, ?, ?)', \
(datetime.datetime(2018,4,23,23,00), 'Test', 'Test2', 2.1, 11.1))

对此:

c.execute('insert into mytable (date, title, custom, x, y)values(?, ?, ?, ?, ?)', \
(datetime.datetime(2018,4,23,23,00), 'Test', 'Test2', 2.1, 11.1))

答案 2 :(得分:0)

示例解决方案

cursor.execute('CREATE TABLE vehicles_record (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)')

上面的SQLite3查询

cursor.execute("INSERT INTO vehicles_record(name) VALUES(?)", (name))

结果

  

id为1,名称将为名称var的值,即最后一列的当前时间戳。