我有一个Python类:
class Database:
conn = sqlite3.connect(‘database.db’)
c = conn.cursor()
def __init__(self):
pass
在这个类中,我有多个方法,我将在数据库类中使用,例如:
def create_table(self, table_name, *args):
pass
def add_user(self):
pass
def remove_user(self):
pass
等等。我的问题是:如果我不确定我将有多少列,我该如何在"create_table"函数中使用*args。例如,我知道我将有第一列、最后一列和付费列,而我的功能将是这样的:
def create_table(self, table_name, *args):
c.execute("""CREATE TABLE ‘{}’ (‘{}’ text, ‘{}’ text, ‘{}’
integer).format(self.table_name, self.first, self.last, self.pay)”””)
c.commit()
所以,如果我想创建表,我可以这样做:
Item = Database()
Item.create_table('employees', ‘First_name’, ’Last_name’, 100000)
但是,如果我不知道我会有多少列呢?感谢
def create_table(self, tableName, *args,):
columns = ''
for i in args:
columns += i
columns += ' '
message = '"""CREATE TABLE {} ({})"""'.format(tableName, columns[:-1])
return message
print(create_table('employes','first','text,','last','text',','pay','integer'(
不确定列的变量有多大;或者时间帧。似乎你已经有了一组基本的定义,然后,一个新的列弹出。所以假设你的表从你上面提到的4开始。
我们首先运行create表,然后在文件上循环,边更新边更新,如果我们找到一个新列,我们运行ALTER table tableName ADD column_name数据类型,然后显然基于键进行更新。
或者,你可以按照qafrombayarea的建议,从开始到结束,一次完成创建。我们的json文件没有那么严格。