我从逗号分隔的文本文件中读取数字,其中一些数字在000000084表格中。这些文件被添加到messageclass中,然后放入SQLite数据库中。我的问题是SQLite将这些000000084保存为84,即使我将表列创建为字符串。你知道吗
输入文件
something,000000018,213123
somethingelse,000000025,213123
创建数据库:
def createDatabase(databasepath):
con = lite.connect(databasepath)
with con:
cur = con.cursor()
cur.execute("CREATE TABLE staticMessage(userid string)")
消息类:
class StaticMessage:
def __init__ (self, userid):
self.userid = userid
正在从文件中提取消息:
def extractStaticMessages(filepath):
global staticMessage
staticMessage = []
lengths = []
f = open(filepath, 'r')
for line in f:
newline = line.split(",")
message = StaticMessage(newline[1])
staticMessage.append(message)
正在将消息写入数据库:
def writeStaticToDatabase(databasepath):
con = lite.connect(databasepath)
con.isolation_level = None
with con:
cur = con.cursor()
cur.execute('BEGIN TRANSACTION')
for i in range(0, len(staticMessage)):
cur.execute("INSERT INTO staticMessage(userid) VALUES(?)",
(staticMessage[i].userid)
cur.execute('COMMIT')
当我用f.ex查询我的数据库时:
select userid from staticMessage where userid='000000084'
我得到84
这对我来说是一个很大的烦恼,因为我想查询我的数据库以获得少于9位数的用户ID。你知道吗
TL/DR:当插入SQLite时,前导零会去哪里?你知道吗
SQLite不强制强列类型。相反,SQLite使用了一种称为类型相似性的东西:有一种首选的存储类型,它是从列声明和一些内部规则派生的,但是您可以很好地以数字形式存储文本,反之亦然。你知道吗
official documentation清楚地解释了确定用于存储数据的类型的规则:
由于您的列被声明为“string”,无法派生到某个特定的类型关联,SQLite将尽可能从规则5中将数据存储为数字。因此,如果可以将值转换为数值,则删除前导零。你知道吗
但是请注意,您可以存储文本(例如:“t00000084”),而不会出现任何问题,因为SQLite将无法将其转换为数字(首选类型关联),而是将其存储为文本。你知道吗
考虑到我们的特殊需要,您应该使用textaffinity声明您的列。即使用包含字符串
CHAR
、CLOB
或TEXT
类型的类型(规则2)。你知道吗000000084
不是数字,84
是。您希望将这些存储在SQLite的文本数据字段中。你知道吗相关问题 更多 >
编程相关推荐