How do I create a MySQL database in PythonAnywhere?
How to Create a MySQL Database in PythonAnywhere
PythonAnywhere provides a MySQL database for its users, but you need to set it up first. Follow these steps:
🔹 Step 1: Log in to PythonAnywhere
- Go to PythonAnywhere and log in.
- Navigate to the Databases tab.
🔹 Step 2: Create a New MySQL Database
- Click "Add a new MySQL database".
- Choose a database name (e.g.,
mydatabase
). - Click Create.
- PythonAnywhere will generate:
- A database name (e.g.,
your_username$mydatabase
). - A MySQL username (same as your PythonAnywhere username).
- A MySQL password (auto-generated, but you can reset it).
- A MySQL host (usually
your_username.mysql.pythonanywhere-services.com
).
- A database name (e.g.,
🔹 Step 3: Connect to MySQL from PythonAnywhere Console
To check if the database is working, open a Bash console in PythonAnywhere and run:
Enter your MySQL password when prompted.
To list databases:
To switch to your database:
🔹 Step 4: Connect to MySQL from a Flask App
Install mysql-connector-python
(if not already installed):
Then, create a Python script (app.py
):
Run the script:
🔹 Step 5: Access MySQL from PythonAnywhere Web App
If you're deploying a Flask app on PythonAnywhere:
- Go to "Web" and create a new Flask app.
- Make sure
app.py
uses the correct MySQL hostname (notlocalhost
butyour_username.mysql.pythonanywhere-services.com
). - Restart the web app after changes.
✅ Final Checklist
✔ Use your full database name (your_username$mydatabase
).
✔ Use PythonAnywhere’s MySQL hostname (your_username.mysql.pythonanywhere-services.com
).
✔ Avoid using localhost
in your connection string.
Let me know if you need further help! 🚀
Testing the MySQL Database
mysql> use ashishjaindrive1$default Database changed mysql> mysql> create table users (name varchar(100)); Query OK, 0 rows affected (0.02 sec) mysql> insert into users values('ram'); Query OK, 1 row affected (0.01 sec) mysql> insert into users values('ravan'); Query OK, 1 row affected (0.00 sec) mysql> commit; Query OK, 0 rows affected (0.00 sec) mysql> How to install python-dotenv? 12:23 ~/mysite $ pip install python-dotenv Defaulting to user installation because normal site-packages is not writeable Looking in links: /usr/share/pip-wheels Collecting python-dotenv Downloading python_dotenv-1.0.1-py3-none-any.whl (19 kB) Installing collected packages: python-dotenv Successfully installed python-dotenv-1.0.1 12:25 ~/mysite $
No comments:
Post a Comment