Python 将值插入SQLite表时强制使用数据类型(BLOB或文本)

Python 将值插入SQLite表时强制使用数据类型(BLOB或文本),python,sqlite,Python,Sqlite,最近,我对SQLite数据库中的以下问题感到困惑:我有一个表,其中有两行显然相同。但是,以下语句仅检索到两行中的一行: SELECT "mycolumn" FROM "mytable" WHERE "mycolumn" == 'identical values'; 显然,mycolumn中的值是相同的,它们甚至有相同的十六进制值。但是,我发现他们的数据类型不同: SELECT "mycolumn", TYPEOF("mycolumn"), QUOTE("mycolumn") FROM "myt

最近,我对SQLite数据库中的以下问题感到困惑:我有一个表,其中有两行显然相同。但是,以下语句仅检索到两行中的一行:

SELECT "mycolumn" FROM "mytable" WHERE "mycolumn" == 'identical values';
显然,mycolumn中的值是相同的,它们甚至有相同的十六进制值。但是,我发现他们的数据类型不同:

SELECT "mycolumn", TYPEOF("mycolumn"), QUOTE("mycolumn") FROM "mytable";
一行给我一个水滴,另一行给我文本


SQLite如何确定是否将值存储为BLOB而不是文本?我使用python2.7-sqlite3创建了数据库,它创建了BLOB行,然后使用sqlitebrowser添加了“相同”行。但是,我希望能够强制python使用文本类型,或者找到一种与BLOB进行比较的方法。有这样的方法吗?

SQLite使用您提供的数据类型存储值。 由于可能会发生更改,但这不会影响blob

若要插入文本值,请将Python代码更改为使用插入文本值

要修复数据库中的值,只需使用更改的类型重写它们:

更新MyTable 将MyColumn=CASTMyColumn设置为文本 其中typeofMyColumn='blob';
作为对CL.答案的补充,这里有一个最小的Python代码,可以帮助理解如何确定存储或检索的类型:

#!/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

请提供一个适当定制的玩具数据库,例如从SQLite命令行工具以.dump的形式提供。阅读这样一堆原始数据库实际上也可能给你答案。非常感谢你的回答!我想我的sqlite3.text\u工厂也有问题。我的text\u工厂是sqlite3.Binary,这可能解释了为什么我在获取结果时获取缓冲区而不是字符串,即使存储值格式是text而不是BLOB。我正在按照Yunnosch的要求编写一个最小的python示例,以便对其他有相同问题的人更加清晰。