Monday, March 17, 2025

Testing Connection With PythonAnywhere Hosted MySQL DB

To See All Articles About Technology: Index of Lessons in Technology

Setup

$ pip install mysql-connector-python $ pip install sshtunnel

Code

import mysql.connector import sshtunnel # Set SSH timeout values sshtunnel.SSH_TIMEOUT = 10.0 sshtunnel.TUNNEL_TIMEOUT = 10.0 with sshtunnel.SSHTunnelForwarder( ('ssh.pythonanywhere.com', 22), # Correct SSH host format ssh_username='ashishjain1547', ssh_password='***', remote_bind_address=('ashishjain1547.mysql.pythonanywhere-services.com', 3306) ) as tunnel: print("✅ SSH Tunnel established") try: print("🔄 Attempting to connect to database...") # Open MySQL connection via the tunnel connection = mysql.connector.connect( user='ashishjain1547', password='***', host='127.0.0.1', port=tunnel.local_bind_port, database='ashishjain1547$dev_keshav', connection_timeout=30 # Increased timeout for stability ) print(connection) if connection.is_connected(): print("✅ Database connection successful!") # Create cursor cursor = connection.cursor() # Create 'users' table create_table_query = """ CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL ) """ cursor.execute(create_table_query) print("✅ Table 'users' created successfully!") # Insert sample data into the table insert_data_query = """ INSERT INTO users (username) VALUES ('Alice'), ('Bob'), ('Charlie') """ cursor.execute(insert_data_query) connection.commit() print("✅ Sample data inserted successfully!") # Display data from the table cursor.execute("SELECT * FROM users") records = cursor.fetchall() print("📋 Users Table Data:") for row in records: print(f"ID: {row[0]}, Username: {row[1]}") else: print("❌ Database connection failed.") except mysql.connector.Error as e: print(f"❌ Error connecting to database: {e}") finally: if 'connection' in locals() and connection.is_connected(): connection.close() print("✅ Database connection closed.")

Output

1st Run On my Ubuntu laptop
3rd run on my Windows laptop
Ref
Tags: Cloud,Python,Database,Technology,

No comments:

Post a Comment