7

I'm trying to create a Web application using flask and Flask-SQLAlchemy, I have the following code

from flask.ext.sqlalchemy import  SQLAlchemy
from flask import Flask

app= Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqldb://root:[email protected]/testdb'
db = SQLAlchemy(app)

When I run db.create_all() from command line, I get "unknown database 'testdb'" error.

I'm working on Ubuntu but the code above works on my Windows machine.

I've tried adding the port number, removing the python connector but nothing works. Below is the stack trace

 File "/usr/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 81, in Connect
     return Connection(*args, **kwargs)
 File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 187, in __init__
     super(Connection, self).__init__(*args, **kwargs2)
 sqlalchemy.exc.OperationalError: (OperationalError) (1049, "Unknown database 'testdb'") None None

2 Answers 2

19

I would suggest that the database 'testdb' does not exist.

SQLAlchemy will not actually create the database for you. You have to connect to an existing database. It will then create all the tables.

Joe

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

2 Comments

Thanks! While in the book "Essential SQLAlchemy" there's an example where SQLLite database is created this way (metadata.create_all()).
@Olia_Pavliuk it has been a while since I've use SQLAlchemy. SQLite databases are just files on disk so it's a little different.
5

You can create DB like this:

url = 'mysql://%s:%s@%s' % (USER, PASSWORD, HOST)
engine = sqlalchemy.create_engine(url)  # connect to server

create_str = "CREATE DATABASE IF NOT EXISTS %s ;" % (DATABASE)
engine.execute(create_str)
engine.execute("USE location;")
db.create_all()
db.session.commit()

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.