0
votes

Everytime I try to create a table in the datable I created titled 'tutorial' I get an error. Here is my python code :

import sqlite3

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

c=conn.cursor()

def create_table():
c.execute("CREATE TABLE example(Language VARCHAR , Version REAL, Skill TEXT)")


def enter_data():

     c.execute("INSERT INTO example VALUES('Python',3.3,'Intermediate')")
     c.execute("INSERT INTO example VALUES('Python',2.7,'Beginner')" )

     c.execute("INSERT INTO example VALUES('Python',3.4,'Expert')" )
     conn.commit()

   enter_data()



  #conn.close()

And here is the error that appears when I run the code:

Traceback (most recent call last): File "C:/Users/Pentazoid/Desktop/Become a professional python programmer/Section 2 web python programming/insert_data.py", line 19, in enter_data() File "C:/Users/Pentazoid/Desktop/Become a professional python programmer/Section 2 web python programming/insert_data.py", line 13, in enter_data c.execute("INSERT INTO example VALUES('Python',3.3,'Intermediate')") sqlite3.OperationalError: no such table: example

What is wrong?

3

3 Answers

0
votes

you're not executing create_table() , so the table is never created and enter_data() can't find it when trying to insert.

0
votes

You should call the function to create the table and commit BEFORE the insert statement:

import sqlite3

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

c = conn.cursor()

def create_table():
    c.execute("CREATE TABLE example(Language VARCHAR , Version REAL, Skill TEXT)")


def enter_data():
    create_table()
    conn.commit()

    c.execute("INSERT INTO example VALUES('Python',3.3,'Intermediate')")
    c.execute("INSERT INTO example VALUES('Python',2.7,'Beginner')" )

    c.execute("INSERT INTO example VALUES('Python',3.4,'Expert')" )
    conn.commit()

enter_data()

However, consider to use SQLAlchemy

0
votes

execute create_table() first in command line for creating table (as was said in above) . Then add enter_data() for inserting.