我试图用Python编写一个程序,请求输入,如果DB中的表存在,则写入它,如果不存在,则创建它。
下面是现有代码:
connection = sqlite3.connect('AnimeScheduleSub.db')
cursor = connection.cursor()
anime_id = input('enter server id')
discord_user_id = int(input('Enter token'))
try:
cursor.execute("SELECT * FROM {}".format(anime_id))
results = cursor.fetchall()
print(results)
except:
command1 = f"""CREATE TABLE IF NOT EXISTS
{anime_id}(discord_user_id INTEGER)"""
cursor.execute(command1)
基本上,它正在做的(或我想要实现的)是尝试循环是为了检查anime_id表是否存在。except循环用于在try循环失败时创建表。
但它不工作,我不知道为什么。如有任何帮助,不胜感激。
command1 = f"""CREATE TABLE IF NOT EXISTS
A{anime_id}(discord_user_id INTEGER)"""
sql不支持仅用数字创建表名。你应该以字母开头,然后用数字。
你应该"问";在数据库中查询表是否存在。
如下所示。
anime_id = input('enter server id')
SELECT name FROM sqlite_master WHERE type='table' AND name='{anime_id}';