Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Using Databases in Python Gettin' CRUD-y With It Add An Entry

Maciej Walczak
Maciej Walczak
5,042 Points

Operational Error

After execution this code in workshop i get an error i can't seem to understand.

#!/usr/bin/env python3

import datetime
import sys
from collections import OrderedDict

from peewee import *

db = SqliteDatabase("diary.db")


class Entry(Model):
    content = TextField()
    timestamp = DateTimeField(default=datetime.datetime.now)

    class Meta:
        database = db

def initialize():
    """Creates a database and a table if the dont exist"""
    db.connect()
    db.create_tables([Entry], safe=True)



def menu_loop():
    """Show the menu"""
    choice = None

    while choice != "q":
        print("Enter 'q' to quit")
        for key, value in menu.items():
            print("{}) {}".format(key, value.__doc__))
        choice = input("Action: ").lower().strip()

        if choice in menu:
            menu[choice]()

def add_entry():
    """Add an entry."""
    print("Enter your entry. Press ctrl+d when done.")
    data = sys.stdin.read().strip()

    if data:
        if input("Save entry? [Y/n] ").lower() != "n":
            Entry.create(content=data)
            print("Saved succesfully!")


def view_entries():
    """View all entries."""


def delete_entries(entry):
    """Deletes an entry."""

menu = OrderedDict([
    ("a", add_entry),
    ("v", view_entries),    
])    

if __name__ == "__main__":
    initialize()
    menu_loop()
File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 2780, in execute_sql                                                            
    cursor.execute(sql, params or ())                                                                                                                                
sqlite3.OperationalError: table entry has no column named content                                                                                                    

During handling of the above exception, another exception occurred:                                                                                                  

Traceback (most recent call last):                                                                                                                                   
  File "diary.py", line 64, in <module>                                                                                                                              
    menu_loop()                                                                                                                                                      
  File "diary.py", line 37, in menu_loop                                                                                                                             
    menu[choice]()                                                                                                                                                   
  File "diary.py", line 46, in add_entry                                                                                                                             
    Entry.create(content=data)                                                                                                                                       
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 3587, in create                                                                 
    inst.save(force_insert=True)                                                                                                                                     
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 3719, in save                                                                   
    pk_from_cursor = self.insert(**field_dict).execute()                                                                                                             
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 2610, in execute                                                                
    return self.database.last_insert_id(self._execute(), self.model_class)                                                                                           
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 2172, in _execute                                                               
    return self.database.execute_sql(sql, params, self.require_commit)                                                                                               
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 2788, in execute_sql                                                            
    self.commit()                                                                                                                                                    
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 2657, in __exit__                                                               
    reraise(new_type, new_type(*exc_value.args), traceback)                                                                                                          
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 115, in reraise                                                                 
    raise value.with_traceback(tb)                                                                                                                                   
  File "/usr/local/pyenv/versions/3.5.0/lib/python3.5/site-packages/peewee.py", line 2780, in execute_sql                                                            
    cursor.execute(sql, params or ())                                                                                                                                
peewee.OperationalError: table entry has no column named content 

3 Answers

Khambrel Davis
Khambrel Davis
24,571 Points

The database may be locked. Delete the database then run the script again. To delete the database, delete diary.db or try just deleting the table.

Maciej Walczak
Maciej Walczak
5,042 Points

Hello Khambrel, what you instructed worked, after deleting the database and execution the script again everything went smooth. Could you please expain how did you know about locking the database?

Khambrel Davis
Khambrel Davis
24,571 Points

Well I encountered this problem before and Kenneth actually warns of the problem arising in the video instruction of PEEWEE. I just read your code and it looked like it was good as far as syntax so I deduced the problem was a familiar one I have faced many times before.

Maciej Walczak
Maciej Walczak
5,042 Points

ahhh, i see now. Thanks for help, and i'll keep all of the above in mind.

I just had the same problem. How do you keep it from locking in the first place. I can't see how the db will be useful if I get locked out of it.