Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

python - Passing list of coulmns and Values in postgresql query

db=postgresql 13

language= python

i have table name = "abc"

coulmn_name=[question_1,question_2,question_3,.....,question_50]
column_values=[1,2,3,......,50]

I need to write a postgresql query to store these values in respective column names basically i need to take list parameters in my query. i have connected to the database using pyscopg2 and i am able to excute queries too. but manually writing column names:

cursor.execute('INSERT INTO user_responses("question_1","question_2","question_3","question_4","question_5","question_6","question_7","question_8","question_9","question_10","question_11","question_12","question_13","question_14","question_15","question_16","question_17","question_18","question_19","question_20","question_21","question_22","question_23","question_24","question_25","question_26","question_27","question_28","question_29","question_30","question_31","question_32","question_33","question_34","question_35","question_36","question_37","question_38","question_39","question_40","question_41","question_42","question_43","question_44","question_45","question_46","question_47","question_48","question_49","question_50") VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',column_values)

above query is working but it is not the correct way i guess . I need something where i can pass list of column names.

       sql_string='INSERT INTO {} '.format(column_name)  

how can i proceed further?please help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It should be INSERT INTO ({}) not INSERT INTO {}. Column names have to be inside round braces.

columns = ["question_1", "question_2", "question_3"]

sql_string = """INSERT INTO user_responses({}) VALUES (%s,%s,%s)""".format(','.join(columns))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...