cmrussell
cmrussell

Reputation: 2112

Flask SQLAlchemy Can't Connect to Database

I have an app that I'm trying to connect to an SQLite DB. I have the db file in the same directory as the app but when I give command to create_all I get the following error:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to open database file (Background on this error at: https://sqlalche.me/e/14/e3q8)

This is a snippet of the code I am using.

    app.config['SECRET_KEY'] = 'dont look at me im a secret'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////C:/Users/me/PycharmProjects/thisproject/database.db'
    app.config['CSRF_ENABLED'] = True
    app.config['USER_ENABLE_EMAIL'] = False
    
    db = SQLAlchemy(app)
    
    
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        username = db.Column(db.String(50), nullable=False, unique=True)
        password = db.Column(db.String(255), nullable=False, server_default='')
        active = db.Column(db.Boolean(), nullable=False, server_default='0')
    
    
    user_manager = UserManager(app, db, User)

Upvotes: 1

Views: 3779

Answers (2)

cmrussell
cmrussell

Reputation: 2112

I had to change my app file name to 'app.py' then update the path to the db as follows:

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///C:\\Users\\me\\PycharmProjects\\thisproject\\database.db'

In order to get this to work

Upvotes: 0

Paulo
Paulo

Reputation: 10346

I believe truth is onto something here. It seems you are not specifying the path to the sqlite database correctly.

Your path should look like:

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///C:\\Users\\me\\PycharmProjects\\thisproject\\database.db'

Upvotes: 2

Related Questions