[英]Is there a way to input columns into a db iteratively with python sqlite3?
def db_include(path, filename):
full_file_path = path + filename
patterns = pattern_retrieval(full_file_path)
db_file = 'sequencesdb.db'
conn = sqlite3.connect(db_file)
try:
c = conn.cursor()
columns = list()
columns_data = list()
#create table
for key, value in patterns.items():
columns.append(key)
columns_data.append(value)
#create column names
c.execute('''CREATE TABLE IF NOT EXISTS sequences ()''')
The pattern_retrieval function returns a dictionary pattern_retrieval 函数返回一个字典
The dictionary is stored in patterns variable字典存储在 patterns 变量中
now I want to create a table called sequences in sequences.db but I want each column to have the name of a key in the patterns variable.This is to help me then insert ints into each column after creating the db.现在我想在sequence.db 中创建一个名为sequences 的表,但我希望每一列在patterns 变量中都有一个键的名称。这是为了帮助我在创建db 后将int 插入到每一列中。
PATTERNS_DB SCHEMA PATTERNS_DB SCHEMA
sequences table序列表
|pattern1|pattern2|pattern3| |模式1|模式2|模式3|
|42 | |42 | 67 | 67 | 78 78
But I want to do all this programatically.但我想以编程方式完成所有这些。
c.execute('''CREATE TABLE IF NOT EXISTS sequences(EMPTY TEXT)''')
for i in range(len(columns)):
addColum = f"ALTER TABLE sequences ADD COLUMN {columns[i] INTEGER}"
c.execute(addColumn)
conn.commit()
You can build the CREATE TABLE statement like this:您可以像这样构建 CREATE TABLE 语句:
s = "CREATE TABLE sequences (" + ', '.join(f"{col} INTEGER" for col in columns) + ")"
c.execute(s)
Or, more secure:或者,更安全:
s = "CREATE TABLE sequences (" + ', '.join(["? INTEGER"]*len(columns)) + ")"
c.execute(s, columns)
Or you could use ALTER TABLE:或者你可以使用 ALTER TABLE:
# columns needs to be a list of tuples for this to work:
c.executemany("ALTER TABLE sequences ADD COLUMN ? INTEGER", columns)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.