Python Forum
I need help creating tables with Sqlite3
Thread Rating:
  • 2 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I need help creating tables with Sqlite3
#1
I wish to make a function that creates tables from a tablename list i provide

import sqlite3


def creat_tables():
    conn = sqlite3.connect('listatest.db')
    c = conn.cursor()
    
    tablelist = ('unu','doi','trei')

    for tablename in tablelist:

        create = 'CREATE TABLE IF NOT EXISTS ' + tablename + ' (numar_par INTEGER PRIMARY KEY, echipa1 TEXT UNIQUE, scor1 TEXT, scor2 TEXT, echipa2 TEXT, '
        'cota FLOAT, miza INT, stare INT)'
        c.execute(create)
I get this error

Error:
"C:\Program Files\Python36\python.exe" "D:/pariuri/python/teste sqlite/TutorialSqlite.py" Traceback (most recent call last): File "D:/pariuri/python/teste sqlite/TutorialSqlite.py", line 6, in <module> creat_tables() File "D:\pariuri\python\teste sqlite\create_tables.py", line 17, in creat_tables c.execute(create) sqlite3.OperationalError: near " ": syntax error Process finished with exit code 1
Reply
#2
Does it fail for the first table, or the second?
Have you tried adding a semicolon to the end of the statement, to let sqlite know it's the end of the statement?  I don't know a lot about sqlite, but it could just be batching all the execute statements together, and actually executing them at the same time when the transaction commits (... which might be when the cursor falls out of scope).

Add a call to print with the sql statement just before calling execute, so we can see if it fails the first time around, or the second.
Reply
#3
Note that your SQL statement is divided on two lines -12 and 13. You have ' at the end of line 12 and rest is orphan string on line 13
Reply
#4
(Sep-25-2017, 05:27 PM)buran Wrote: Note that your SQL statement is divided on two lines -12 and 13. You have ' at the end of line 12 and rest is orphan string on line 13

I did put a print in front of execute as nimalo suggested, and made line 12 and 13 in one line, and this did the job, which is interesting as that is how Pycharm is formating a line that is too long if i just copy/paste it into the interpreter.

Thanks you.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Creating a table in SQLite3 djwilson0495 2 2,016 Aug-10-2020, 03:01 PM
Last Post: djwilson0495
  Creating Tables in SQL danteslion 2 34,463 Jun-22-2019, 08:13 PM
Last Post: Gribouillis
  sqlite3 table structure and db tables pythonNoob 7 4,837 May-16-2018, 02:19 PM
Last Post: pythonNoob

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020