P
P
Pavel Bezobrazov2020-04-19 17:17:36
Python
Pavel Bezobrazov, 2020-04-19 17:17:36

How to set the table name using a variable?

Good day to all. New to DB. I am writing a script that should create a table at a given time. I need its name to be given to a variable.

import psycopg2
a="abc"
cur = con.cursor()
cur.execute('''CREATE TABLE xxx  
         (VM_UUID CHAR(200) PRIMARY KEY NOT NULL,
         VM_NAME CHAR(200),
         CPU INT NOT NULL,
         MEMORY DECIMAL NOT NULL);''')

How can I put the value of variable a instead of xxx?
Thanks in advance. Also, I will not refuse a link to any information about this. I looked at the official website of psycopg, but it’s not there, or I didn’t look well, so poke your nose in the right place.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
1
101-s, 2020-04-20
@rysevpd

I understand you are a beginner in python
like this:

a="abc"
cur = con.cursor()
cur.execute("""CREATE TABLE %s
         (VM_UUID CHAR(200) PRIMARY KEY NOT NULL,
         VM_NAME CHAR(200),
         CPU INT NOT NULL,
         MEMORY DECIMAL NOT NULL)""" % a)

I liked https://pythonworld.ru/ for studying

K
kzoper, 2020-04-19
@kzoper

Inserting values ​​into strings

N
Nikolay, 2020-04-20
@SODINNER

Through {} and format and execute it, or through cur.execute(sql_string, [variable])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question