將字串保存到 sqlite 表中,再次檢索它并將其與原始字串進行比較需要一些過濾器才能作業,我不知道究竟是為什么。
tl;dr 如何從 SQLITE DB 檢索字串資料而不需要過濾器 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')
uj5u.com熱心網友回復:
所以這是你的問題:fetchall回傳一個tuples串列。這意味著將它們轉換為字串會在每一行周圍放置討厭的括號,并在每行的每個元素之間放置逗號。如果您想從每一列中檢索原始資訊,可以通過索引元組來完成:
entries = cursorObj.fetchall()
first_row = entries[0]
first_item = first_row[0]
print(first_item)
這應該只列印資料庫中第一行和第一列的內容。如果沒有,請告訴我!
大衛
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/326790.html
