Friday, April 6, 2018

How to setup MySQL Database on PythonAnyWhere.com

Hello there,
PythonAnyWhere.com is one of the platforms that allows you to easily host scripts written in python. In this post, I will show how to setup a database server on the platform and load in data from a simple python script.

There are several databases supported on the PythonAnyWhere.com platform. the common once are:-
1- SQLite (a server less database that requires not setup at all)
2- MySQL (a server based database available for free account holders)
3- PostgreSQL (a server based database available for paid account holders)

I will be using the MySQL database for this demonstration as it is the one that requires setup and is available to every on account (free and paid accounts).

Step 1:
If you haven't already, create a free account on PythonAnyWhere.com


Step 2:
Login to your account dashboard and go to the "Databases" tab. Then Create a database by specifying the Database name and MySQL password




Step 3:
After creating a Database name and MySQL password, you should have a MySQL Console added to you list of consoles under the console tab. The name will look like this: MySQL: username$dbname



Open it and you should have your MySQL console running just like mine...



Step 4:
Now, you can enter MySQL commands to interact with your MySQL database via the console. For example, lets display the databases and tables in our account by entering: show databases; and show tables;



Step 5:
To create a table, enter this query....
CREATE TABLE test_table (
id int,
member_id int,
status varchar(255)
);
The above query creates a new table named "test_table" with three fields namely; 'id', 'member_id' and 'status'. The 'id' and 'member_id' fields are integer fields while 'status' is a varchar.



Connecting your app/script:
To connect your web application or any python .py script to the database, you simply
host='username.mysql.pythonanywhere-services.com'
user='username'
pass='password'
database='username$databasename'
For example if you are using the MySQLdb module, you connection will look like this:-
conn = MySQLdb.connect(
    host='username.mysql.pythonanywhere-services.com',
    user='username',
    passwd='pass123',
    db='username$your_db_name')


That is it!
You have learned how to create a MySQL database on PythonAnyWhere.

Note: To create another database, just repeat step 2 above. Also, note that whatever database name and password you specified at that point are the credentials you will use if you a connecting to the database from an external script such as python .py script.

No comments:

Post a Comment