0

I'm learning sqlite3 in python with this tutorial http://zetcode.com/db/sqlitepythontutorial/. I started "Inserting data" chapter. I ran this code:

import sqlite3 as lite
import sys

con = lite.connect('test.db')

with con:

    cur = con.cursor()    
    cur.execute("CREATE TABLE Cars(Id INT, Name TEXT, Price INT)")
    cur.execute("INSERT INTO Cars VALUES(1,'Audi',52642)")
    cur.execute("INSERT INTO Cars VALUES(2,'Mercedes',57127)")
    cur.execute("INSERT INTO Cars VALUES(3,'Skoda',9000)")
    cur.execute("INSERT INTO Cars VALUES(4,'Volvo',29000)")
    cur.execute("INSERT INTO Cars VALUES(5,'Bentley',350000)")
    cur.execute("INSERT INTO Cars VALUES(6,'Citroen',21000)")
    cur.execute("INSERT INTO Cars VALUES(7,'Hummer',41400)")
    cur.execute("INSERT INTO Cars VALUES(8,'Volkswagen',21600)")

Then I made this in OS X terminal:

sqlite> .mode column  
sqlite> .headers on
sqlite> SELECT * FROM Cars;

And this happened:

Error: no such table: Cars

I don't know why. Test.db and the script are in the same direction. I was searching for this problem and I only found solutions that I don't understand.

4
  • works for me. try adding cur.execute("DROP TABLE IF EXISTS Cars") before CREATE TABLE Commented Apr 18, 2016 at 21:16
  • Make sure you start the shell with sqlite3 test.db or if you just ran sqlite3 that you first .open test.db. Commented Apr 18, 2016 at 22:31
  • now the terminal shows "...>" :( Commented Apr 19, 2016 at 8:14
  • and I found that it creates test.db in two folders: my main folder and where are the python scripts Commented Apr 19, 2016 at 8:19

1 Answer 1

1

I ran into this recently, as I am also learning python and sqlite. From what I can tell, the modifications you make to a database remain in memory until you commit your changes. You'll also want to close your database when you no longer need access to it. I'm not sure if the with con: approach will commit or even close the database for you. Add these lines to the end of your script.

con.commit()
con.close()

You can witness these commands being used in the second code blurb on the python sqlite3 documentation page.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.