Create a table in sqlite using a variable

0

I want to program a function in python that creates tables in a sqlite database from a variable. This code does not work:

def creartabla(nombretabla):
    connectionObject  = sqlite3.connect("jez")
    cursorObject = connectionObject.cursor()
    createTable = "CREATE TABLE nombretabla (id int, nombre varchar(40))"              
    cursorObject.execute(createTable)

How should I write it? Thanks.

    
asked by Eduardo 06.11.2018 в 20:45
source

2 answers

0

Solved using% s after create table and% tablename at the end of the expression. Thanks for the help.

    
answered by 06.11.2018 в 22:58
0

One of the ways to pass variables to an SQLite statement would be as follows:

def creartabla(nombretabla):
    connectionObject  = sqlite3.connect("jez")
    cursorObject = connectionObject.cursor()
    createTable = "CREATE TABLE '%s'(id int, nombre varchar(40))" % nombretabla             
    cursorObject.execute(createTable)
    connectionObject.commit()

Remember that just at the end of the sentence you must make a commit() if it is not registered in the Database.

If you need more information you can visit the library page of SQLite

    
answered by 15.11.2018 в 15:42