简体   繁体   English

我无法通过从列表中获取列名来创建表?(postgresql/psycopg2)

[英]I can't create table by getting column names from a list?(postgresql/psycopg2)

I have prepared two sample lists below.我在下面准备了两个示例列表。 My goal is to create a table with these two lists in postgresql.id will be bigserial primary key.but I keep getting errors.我的目标是在 postgresql.id 中创建一个包含这两个列表的表将是 bigserial 主键。但我不断收到错误。 how do you think i can do that?你觉得我怎么能做到?

My example list and code:我的示例列表和代码:

my_column_name = ['id','first name','surname','age']

data= [{'Jimmy', 'wallece', 17}]


connection = psycopg2.connect(user = "postgres",
                              password = "Sabcanuy.1264",
                              host="127.0.0.1",
                              port="5432",
                              database="postgres")

cursor = connection.cursor()


create_table_query = '''CREATE TABLE unit_category_report (ID BIGSERIAL  PRIMARY KEY , 
my_columne_name); '''

Strings cannot access variables and their values.字符串不能访问变量及其值。

I'm not 100% sure this will work but you can try:我不是 100% 确定这会起作用,但您可以尝试:

my_column_name =['id','first_name','surname','age']

create_table_query = '''CREATE TABLE unit_category_report (ID BIGSERIAL  PRIMARY KEY , %s); ''' % (my_column_name)

Or...或者...

create_table_query = '''CREATE TABLE unit_category_report (ID BIGSERIAL  PRIMARY KEY , {0}); '''.format(my_column_name)

You may have to switch to double quotes from the triple single quote.您可能必须从三重单引号切换到双引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM