聲音就像數據庫一樣。只需import sqlite3
。
創建表(將它在當前目錄下保存爲serials.db
):
import sqlite3
conn = sqlite3.connect('serials.db') #Will create a new table as it doesn't exist right now
cur = conn.cursor() #We will use this to execute commands
cur.execute('''CREATE TABLE serials_tb (serial text)''') #for more than one column add a comma, as in a tuple, and write '[COL_NAME] [COL_TYPE]' without the apostrophes. You might want (as I suppose you only want a serial to be used once) to define it as a primary key
conn.commit()
conn.close()
增加串行:
import sqlite3
conn = sqlite3.connect('serials.db') #Will connect to the existing database
cur = conn.cursor()
data = ('MY_SERIAL',) #a tuple
cur.execute('''INSERT INTO serials_tb VALUES (?)''', data)
conn.commit()
conn.close()
選擇串行(看它是否已經存在):
import sqlite3
conn = sqlite3.connect('serials.db') #Will connect to the existing database
cur = conn.cursor()
data = ('MY_SERIAL',)
qry = cur.execute('''SELECT * FROM serials_tb WHERE serial=?''', data)
#You can iterate over it and get a tuple of each row ('for row in qry:')
#But to check if a col exists, in your case, you can do so:
if len(qry.fetchall()) != 0:
#The serial is used
else:
#The serial isn't used
注意:顯然,您無需每隔一段時間輸入sqlite3
時間(僅在每個文件中,但不是每次執行命令時,也不需要每次執行命令都要連接或關閉連接。在需要時提交更改,在開始時連接並在結束時關閉連接。 欲瞭解更多信息,你可以閱讀here。
我不敢相信我自己沒有想到它。非常感謝你,正是我需要的 –