简体   繁体   中英

Python and sqlite3 - no such table

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM