Search code examples
pythonsqlitedynamically-generated

sqlite3 python generate tables


I am trying to generate tables based off the paramaters of a function. To generate the table I thought of passing a string of what I wanted to be executed as the following function:

conn = sqlite3.connect('tutorial.db')

c = conn.cursor()

def create_table(name, unix, datestamp, keyword, value):

    command = "CREATE TABLE IF NOT EXISTS " + name + "(" + unix + " REAL, " + datestamp + " TEXT, " + keyword + " TEXT, " + value + " REAL)"

    c.execute('CREATE TABLE' + command)

However when I run the command:

create_table('new','boy','girl','joy','joe')

I get error: Traceback (most recent call last): File "C:\Users\David\Documents\learn_sql_\learn_sql.py", line 22, in create_table('new','boy','girl','joy','joe') File "C:\Users\David\Documents\learn_sql_\learn_sql.py", line 12, in create_table c.execute('CREATE TABLE' + command) sqlite3.OperationalError: near "TABLECREATE": syntax error

Thoughts?

Thanks


Solution

  • try with this :

    import sqlite3
    
    conn = sqlite3.connect('tutorial.db')
    
    c = conn.cursor()
    
    def create_table(name, unix, datestamp, keyword, value):
    
        #c.execute('CREATE TABLE' + command)
        cmd = "CREATE TABLE IF NOT EXISTS %s(%s real,%s text,%s text,%s real)" % (name,unix,datestamp,keyword,value)
        print(cmd)
        c.execute(cmd)
    
    create_table('new','boy','girl','joy','joe')