Connecting to MySQL via Python and I have contradictory results - mysql

I am trying to connect to a MySQL database hosted on Python Anywhere. In the below example connection.get_server_info() returns a result however connection.is_connected() returns False and I am unsure why.
Here is my code:
import mysql.connector
import sshtunnel
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='USERNAME', ssh_password='PASSWORD',
remote_bind_address=('USERNAME.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = mysql.connector.connect(
user='USERNAME', password='DB_PASSWORD',
host='127.0.0.1', port=tunnel.local_bind_port,
database='USERNAME$default',
)
db_info = connection.get_server_info()
if connection.is_connected():
print('Connected to MySQL DB...version on ', db_info)
else:
print('Failed to connect.')
print(db_info)
connection.close()
I have a paid account on Python Anywhere so SSH tunneling should be possible

It's because you're trying to access the SSH tunnel after it has been closed; the tunnel is closed when you exit the with block, so anything that uses the connection needs to be indented so that it is contained within it. Your code above look like this:
import mysql.connector
import sshtunnel
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='USERNAME', ssh_password='PASSWORD',
remote_bind_address=('USERNAME.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = mysql.connector.connect(
user='USERNAME', password='DB_PASSWORD',
host='127.0.0.1', port=tunnel.local_bind_port,
database='USERNAME$default',
)
db_info = connection.get_server_info()
if connection.is_connected():
print('Connected to MySQL DB...version on ', db_info)
else:
print('Failed to connect.')
print(db_info)
connection.close()

Related

Pythonanywhere giving MySQL connection error even without time delay

I am trying to connect to my pythonanywhere DB from a local python file, using the following code.
import MySQLdb, sshtunnel
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0
queryAdd = ("INSERT INTO `****$geo***`.O***"
"(name, address) "
"VALUES (%s, %s)")
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='*******', ssh_password='*******',
remote_bind_address=('*****.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = MySQLdb.connect(
user='******',
passwd='********',
host='127.0.0.1', port=tunnel.local_bind_port,
db='****$geo******',
)
cursor = connection.cursor()
for row in dl:
tup=(row['name'],row['address'])
cursor.execute(queryAdd, tup)
connection.commit()
However, as soon as the code is run, I get the following error:
MySQLdb._exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query')
There is no delay between creating the connection and running the query. What am I doing wrong?
You need to do everything inside your with block as the tunnel is gone when you go outside of the context.

Why do I get TCP/IP error when trying to create DB in my Lambda?

So I'm trying to deploy my Django project using lambda, with zappa. I'm using MySQL for DB engine. Now after doing some research, I realized that I needed to create a custom Django command to create DB, since I'm using MySQL. So I created crate_db command, zappa updated, then ran zappa manage dev create_db. Then I got this error: 2004 (HY000): Can't create TCP/IP socket (97)
below is my create_db.py file, for your information.
import sys
import logging
import mysql.connector
import os
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
rds_host = os.environ.get("MY HOST")
db_name = os.environ.get("")
user_name = os.environ.get("MY USERNAME")
password = os.environ.get("MY PASSWORD")
port = os.environ.get("3306")
logger = logging.getLogger()
logger.setLevel(logging.INFO)
class Command(BaseCommand):
help = 'Creates the initial database'
def handle(self, *args, **options):
print('Starting db creation')
try:
db = mysql.connector.connect(host=rds_host, user=user_name,
password=password, db="mysql", connect_timeout=10)
c = db.cursor()
print("connected to db server")
c.execute("""CREATE DATABASE bookcake_db;""")
c.execute("""GRANT ALL ON bookcake_db.* TO 'ryan'#'%'""")
c.close()
print("closed db connection")
except mysql.connector.Error as err:
logger.error("Something went wrong: {}".format(err))
sys.exit()
Any ideas? Thanks.

How to change the authentication configuration of mysql connector to python?

I was trying to connect MySQL with python via the following code.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="qwerty",
auth_plugin="mysql_native_password"
)
print(mydb)
It gave me the following error:-
mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported
My connector version is:-
C:\Users\samar>pip install mysql-connector-python
Requirement already satisfied: mysql-connector-python in c:\users\samar\anaconda3\lib\site-packages (8.0.21)
import pymysql
host="localhost"
user="root"
passwd="qwerty"
db="<give db name"
def dbConnectivity(host,user, passwd, db):
try:
db = pymysql.connect(host=host,
user=user,
passwd=passwd,
db=db)
cursor = db.cursor()
print("Great !!! Connected to MySQL Db")
return cursor
except pymysql.Error as e:
print("Sorry !! The error in connecting is:" + str(e))
return str(e)
dbConnectivity(host,user,passwd,db)

Error when connecting to MySQL database using mysql.connector

I am trying to connect to a MySQL database using mysql.connector:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="user",
password="password",
database="database"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM table")
myresult = mycursor.fetchone()
print(myresult)
I get this error message:
errno=2003, values=(self.get_address(), _strioerror(err)))
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on'localhost:3306'(10061 No connection could be made because the target machine actively refused it)
Does this mean that there something wrong with the database credentials?

cursor() and connection() methods are not working while trying to connect MySQL via Python(using Pycharm)

I am trying to connect MySQL database via python. I initially installed mysql-connector which did not work. later I installed mysql-connector-python and connection was successful. But when I tried to use cursor(), getting error:
Code:
import _mysql_connector
mydb = _mysql_connector.MySQL().connect(host="localhost", user="root", password="1234")
mycursor = mydb.cursor()
mycursor.execute("show databases")
Error: AttributeError: 'NoneType' object has no attribute 'cursor'
**
Solved(used alternate module: MySQLdb)
:**
--- mysql.connector did not work for me, I used an alternate module MySQLdb which I installed using pip3 install mysqlclient.
code:
import MySQLdb
mydb = MySQLdb.connect(user="root", host="localhost", password="1234", database="mydatabase")
cursor = mydb.cursor()
cursor.execute("select * from tableName")
for i in cursor:
print(i)
cursor.close()
mydb.close()
You're trying to connect using C Extension Module. Here is basic Connector example:
import mysql.connector
mydb = mysql.connector.connect(user='root', password='1234', host='localhost', database='myDatabase')
cursor = mydb.cursor()
cursor.execute('show databases')
/*
.
.
.
*/
cursor.close()
mydb.close()