一、安装SQLite
1、下载sqlite
2、解压安装包
3、设置环境变量
二、快速创建库和表的代码
import sqlite3
import os
# 数据库文件名
db_name = 'StarVerification.db'
new_db_name_base = 'StarVerification_old.db'
new_db_name = new_db_name_base
# 检查数据库文件是否存在
db_exists = os.path.exists(db_name)
# 如果数据库文件存在,按顺序重命名为StarVerification_old2,StarVerification_old3 ...
if db_exists:
counter = 1
while os.path.exists(new_db_name):
counter += 1
new_db_name = f'db{counter}.db'
os.rename(db_name, new_db_name)
db_name = new_db_name
print(f"数据库文件已重命名为 {new_db_name}")
# 连接到SQLite数据库(如果数据库不存在,会自动创建)
db_name = 'StarVerification.db'
conn = sqlite3.connect(db_name)
cursor = conn.cursor()
# 如果数据库文件不存在,创建name表
if not db_exists:
cursor.execute('''
CREATE TABLE name (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL
)
''')
print("数据库和表已创建。")
else:
# 检查是否存在name表
cursor.execute('''
SELECT name FROM sqlite_master WHERE type='table' AND name='name'
''')
table_exists = cursor.fetchone()
if not table_exists:
cursor.execute('''
CREATE TABLE name (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL
)
''')
print("表已创建。")
else:
print("表已存在。")
# 插入username和password
username = 'xxxx'
password = '123456'
query = "INSERT INTO name (username, password) VALUES (?, ?)"
cursor.execute(query, (username, password))
print("数据已插入。")
# 提交事务并关闭连接
conn.commit()
cursor.close()
conn.close()
标签:sqlite,name,exists,Python,数据库,db,cursor,库和表,new
From: https://blog.csdn.net/weixin_52037378/article/details/140958676