我正在构建一个数据库应用程序作为练习。我想通过构造SQL命令来使用一组函数来提供创建,更新,添加和删除功能,这些命令将传递给处理数据库连接,执行,提交和关闭的连接器函数。
我尝试使用“ SQL命令%s”,(某些) 也尝试了以上但?代替%s 这似乎是正确的语法,但通常直接包含在execute函数中
import sqlite3
class Connector:
def __init__(self,name):
self.db_name = name
self.table = "book"
def change_table(self,table):
self.table = table
def create_db(self):
command = "CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, isbn INTEGER)"
return self.generic_connector(command)
def insert(self,title,author,year,isbn):
try:
title = str(title)
author = str(author)
isbn = int(isbn)
year = int(year)
command = "INSERT INTO book VALUES(:title,:author,:year,:isbn)",
{"title": title,"author": author,"year": year,"isbn":isbn}
print(command)
return self.generic_connector(command)
except ValueError:
return 1
def generic_connector(self,command):
command = command[0], command[1]
print(command)
try:
conn = sqlite3.connect(self.db_name)
cur = conn.cursor()
cur.execute(command)
rows = cur.fetchall()
conn.commit()
conn.close()
return rows
except (ValueError, SyntaxError):
print("oops")
当我打印命令时,我希望看到:-
"CREATE TABLE IF NOT EXISTS table_name (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, isbn INTEGER)"
相反,我得到了这个:-
("CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, isbn INTEGER)", (self.table,))