从没有字符串格式的sqlite中检索文本进行比较



将字符串保存到sqlite表中,再次检索并将其与原始的字符串进行比较,需要一些过滤器才能工作,我不知道为什么。

tl,博士我如何从SQLITE数据库检索字符串数据,而不需要过滤器Nr 3,因为它的危险更复杂的字符串?


import sqlite3
RAWSTRING = 'This is a DB Teststing'
# create database and table
currentdb = sqlite3.connect('test.db')
currentdb.execute('''CREATE TABLE tickertable (teststring text)''')
# enter RAWSTRING into databasse
currentdb.execute('''INSERT INTO tickertable VALUES(?);''', (RAWSTRING,))
# get RAWSTRING from database
cursorObj = currentdb.cursor()
cursorObj.execute('SELECT * FROM tickertable')
DB_RAWSTRING = cursorObj.fetchall()
currentdb.commit()
currentdb.close()
# Prints This is a DB Teststing
print('originalstring : ', RAWSTRING)
# Prints [('This is a DB Teststing',)]
print('retrieved from DB: ', DB_RAWSTRING)
# Get first entry from List because fetchall gives a list
FILTER1_DB_RAWSTRING = DB_RAWSTRING[0]
# Convert the Listelement to String because its still a listelement and comparing fails to string
FILTER2_DB_RAWSTRING = str(FILTER1_DB_RAWSTRING)
# Remove annoying db extra characters and i dont know why they exist anyway 
FILTER3_DB_RAWSTRING = FILTER2_DB_RAWSTRING.replace("'", "").replace("(", "").replace(")", "").replace(",", "")
if RAWSTRING == FILTER3_DB_RAWSTRING:
print('Strings are the same as they should')
else:
print('String are not the same because of db weirdness')

所以这是你的问题:fetchall返回元组的列表。这意味着将它们转换为字符串会在每行周围加上括号,并在每行的每个元素之间加上逗号。如果希望从每个列检索原始信息,可以通过索引元组来完成:

entries = cursorObj.fetchall()
first_row = entries[0]
first_item = first_row[0]
print(first_item)

这应该只打印数据库中第一行和第一列的内容。如果没有,请告诉我!

大卫

最新更新