创建表时将列名作为变量 [英] column names as variables while creating table
本文介绍了创建表时将列名作为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 python sqlite 的新手,我在创建表查询时遇到了问题.
Iam new to python sqlite, and I have a problem with create table query.
我需要创建一个表,但我将表的列名作为列表.
I need to create a table, but I have the column names of the table as a list.
columnslist = ["column1", "column2", "column3"]
现在,我必须使用上述列创建一个表 MyTable
.但问题是,我事先不知道 columnslist
Now, I have to create a table MyTable
with the above columns. But the problem is, I won't know before hand how may columns are there in columnslist
是否可以使用列列表中给出的列数和名称及其语法创建一个表?
Is it possible to create a table with the number of and name of columns given in columnslist and its syntax?
推荐答案
您可以先将您的列表转换为元组并使用 str.format
:
You can first convert your list to tuple and use str.format
:
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE table_name {}'''.format(tuple(column_list)))
这篇关于创建表时将列名作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文