听起来数据库可以。只是
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
.