我最近对SQLite数据库中的以下问题感到困惑:我有一个表有两个明显相同的行。但是,以下语句仅检索两行中的一行:
SELECT "mycolumn" FROM "mytable" WHERE "mycolumn" == 'identical values';
显然," mycolumn"中的值是相同的(他们甚至有相同的HEX()值)。但是,我发现他们的数据类型不同:
SELECT "mycolumn", TYPEOF("mycolumn"), QUOTE("mycolumn") FROM "mytable";
一行给了BLOB,另一行给了TEXT。
SQLite如何确定是否将值存储为BLOB而不是TEXT?我使用python2.7-sqlite3(创建了BLOB行)创建了数据库,然后使用sqlitebrowser添加了“相同”行。但是,我希望能够强制python使用TEXT类型(或者找到一种与BLOB进行比较的方法)。有这样的方式吗?
答案 0 :(得分:1)
作为CL。答案的补充,这里有一个最小的python2代码,可以帮助理解如何确定存储或检索的类型:
#!/usr/bin/python2
# -*- coding: utf-8 -*-
"""
"""
import sqlite3
c = sqlite3.connect (':memory:')
cc=c.cursor()
cc.execute (''' CREATE TABLE t (a TEXT);''')
def insert_value (a):
#Depending on type (a), the stored data type will be different:
# TEXT for str or unicode
# BLOB for buffer
cc.execute (''' INSERT INTO t (a) VALUES (?); ''', (a,))
c.commit ()
## writing into the database:
print ('Storing a string will store it as TEXT.')
insert_value ('some value')
print ('Storing a buffer will store it as BLOB.')
insert_value (buffer ('some value'))
def read_values ():
## reading from the database: the retrieved value only depends
## of sqlite3.text_factory, not on the stored type
cc.execute (''' SELECT rowid, a, TYPEOF(a) FROM t; ''')
for rowid, retrieved_a, typeof_stored_a in cc.fetchall ():
print ('%d: type of retr. value: %s; type of stored value: %s'%(
rowid,
type(retrieved_a),
typeof_stored_a))
print ('\nUsing text_factory <buffer>: BLOB -> buffer; TEXT -> buffer')
c.text_factory = buffer # (=== sqlite3.Binary)
read_values ()
print ('\nUsing text_factory <str>: BLOB -> buffer; TEXT -> str')
c.text_factory = str
read_values ()
c.close ()
输出:
Storing a string will store it as TEXT.
Storing a buffer will store it as BLOB.
Using text_factory <buffer>: BLOB -> buffer; TEXT -> buffer
1: type of retr. value: <type 'buffer'>; type of stored value: text
2: type of retr. value: <type 'buffer'>; type of stored value: blob
Using text_factory <str>: BLOB -> buffer; TEXT -> str
1: type of retr. value: <type 'str'>; type of stored value: text
2: type of retr. value: <type 'buffer'>; type of stored value: blob
答案 1 :(得分:0)
SQLite使用您提供的数据类型存储值。 (由于column affinity可能会有变化,但这绝不会影响blob。)
如果要插入文本值,请更改Python代码以插入文本值(使用proper types)。
要修复数据库中的值,只需使用更改的类型重写它们:
UPDATE MyTable
SET MyColumn = CAST(MyColumn AS TEXT)
WHERE typeof(MyColumn) = 'blob';