当我将具有整数值的内容存储为字符串时,当我检索它时它突然变成了一个 int。
这就是我所看到的:我用这个存储
db = get_db()
hello = escape(str(request.form['name'])).striptags()
what = escape(str(request.form['content'])).striptags()
db.execute('''insert into entry (
title, content, score, approved, pub_date) values (?, ?, 0, 0,?)''',
[hello,what,int(time.time())])
raise Exception('what')
db.commit()
当我从页面提交时,说 form['name']='1'
和 form['content']='2'
, 异常
、hello==u'1'
和content==u'2'
。到目前为止一切都很好。然后我存储在 DB
中,但是当我去检索时,突然条目类型为 int
1
和 2
。对于任何其他字符串,一切都正确,比如 "lorem ispum"
。
在我的sql schema
中,title
和content
都是string
类型。怎么回事?
最佳答案
请注意,在 SQLite 中使用任何列类型并不能保证此列将被允许仅存储此类型的值 - 它仍然可以存储任何类型的值。
我认为您的情况是您的列具有 INTEGER 或 NUMERIC 亲和性,在这种情况下,SQLite 通常会存储 INTEGER 类型的值。但是,如果您尝试存储无法无损转换为 INTEGER 的数据,SQLite 会自动将其转换为 TEXT。 (或者,您的列可能具有 TEXT 亲和性,但 Python 以某种方式强制此字段将其存储为 INTEGER,如果它看起来像整数的话)。
您可以在 SQLite documentation 中阅读更多相关信息- 滚动到 2.0 类型亲和性。
关于python - flask +Sqlite : Strings that are integers return as type int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14026478/