我的前导零去哪了?

2024-10-03 11:16:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我从逗号分隔的文本文件中读取数字,其中一些数字在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时,前导零会去哪里?你知道吗


Tags: 文件path数据库消息executesqlitedefconnect
2条回答

SQLite不强制强列类型。相反,SQLite使用了一种称为类型相似性的东西:有一种首选的存储类型,它是从列声明和一些内部规则派生的,但是您可以很好地以数字形式存储文本,反之亦然。你知道吗

official documentation清楚地解释了确定用于存储数据的类型的规则:

The affinity of a column is determined by the declared type of the column, according to the following rules in the order shown:

  1. If the declared type contains the string "INT" then it is assigned INTEGER affinity.

  2. If the declared type of the column contains any of the strings "CHAR", "CLOB", or "TEXT" then that column has TEXT affinity. Notice that the type VARCHAR contains the string "CHAR" and is thus assigned TEXT affinity.

  3. If the declared type for a column contains the string "BLOB" or if no type is specified then the column has affinity NONE.

  4. If the declared type for a column contains any of the strings "REAL", "FLOA", or "DOUB" then the column has REAL affinity.

  5. Otherwise, the affinity is NUMERIC.

Note that the order of the rules for determining column affinity is important. A column whose declared type is "CHARINT" will match both rules 1 and 2 but the first rule takes precedence and so the column affinity will be INTEGER.

由于您的列被声明为“string”,无法派生到某个特定的类型关联,SQLite将尽可能从规则5中将数据存储为数字。因此,如果可以将值转换为数值,则删除前导零。你知道吗

但是请注意,您可以存储文本(例如:“t00000084”),而不会出现任何问题,因为SQLite将无法将其转换为数字(首选类型关联),而是将其存储为文本。你知道吗


考虑到我们的特殊需要,您应该使用textaffinity声明您的列。即使用包含字符串CHARCLOBTEXT类型的类型(规则2)。你知道吗

000000084不是数字,84是。您希望将这些存储在SQLite的文本数据字段中。你知道吗

相关问题 更多 >