Error when connecting to MySQL database with Python - python

I am using a simple python function to connect to a MySQL database.I receive an error saying a variable is referenced before it is assigned, but this would not be the case if the connection had successfully established. Why is the connection failing?
I am using Ubuntu Linux 18.04. I am running xampp 7.3 to host the mySQL and apache servers and am using phpmyadmin to access the database.I am running my code with python 3.
This is my code:
import mysql.connector
from mysql.connector import Error
def connect():
""" Connect to MySQL database """
try:
conn = mysql.connector.connect(host='localhost',
database='myDB',
user='xxx',
password='yyy!')
if conn.is_connected():
print('Connected to MySQL database')
except Error as e:
print(e)
finally:
conn.close()
if __name__ == '__main__':
connect()
And this is the error I receive:
Traceback (most recent call last):
File "01_python-mysql-connect.py", line 23, in <module>
connect()
File "01_python-mysql-connect.py", line 19, in connect
conn.close()
UnboundLocalError: local variable 'conn' referenced before assignment
I am expecting a successful connection to the database. I believe something could be wrong with my configurations but don't know where to start in solving the problem. Thank you.

This line
conn = mysql.connector.connect(host='localhost',
database='myDB',
user='xxx',
password='yyy!')
is failing. So conn never gets a value assigned to it. But you have a try...except...finally block and in the finally clause your code is doing conn.close(). But conn hasn't been assigned because the statement that was supposed to assign it a value failed. That is why you are seeing the message local variable 'conn' referenced before assignment. To discover what is wrong, move the call to close out of the finally clause and put it before the except. You can always move it back later.

If the mysql.connector.connect() call fails, conn will not be assigned, hence the "referenced before assignment" exception.
This is an ideal use case for the contextlib.closing context manager, I think. Try something like this:
from contextlib import closing
try:
with closing(mysql.connector.connect(...)) as conn:
if conn.is_connected():
print('Connected to MySQL database')
except Error as e:
print(e)
This will cleanly and reliably take care of closing your connection for you.

Related

remotemysql.com cannot connect with python neither on the site manually

I try to reach to my remotemysql database with my Python script which worked fine first, now it doesn't connect anymore so I went to remotemysql.com/login.php but it gives an error
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
anyone know if its only for me or if remotemysql.com is having problems?
my code for Python should also be fine.
these are random credentials in my code btw.
try:
conn = mysql.connector.connect(
host='remotemysql.com',
database='thydfc2',
user='thydfc2',
password=os.environ.get('databasepass'))
except Error as e:
print(e)
if conn.is_connected():
mycursor = conn.cursor()```

How to share a mysql connection that is inside a function?

I am a beginner in python and mysql. I have a small application written in Python that connects to remote mysql server. There is no issues to connect and fetch data. It works fine then the code is outside a function. As I want to close and open connections, execute different queries from several functions inside my application, I would like to be able to call a function to establish a connection or run a query as needed. It seems that when I create an connection, that connection can not be used outside the function. I would like to implement something like this:
mydbConnection():
....
mydbQuery():
....
connected = mydbConnection()
myslq = 'SELECT *.......'
result = mydbQuery(mysql)
And so on...
Thanks for any direction on this.
import mysql.connector
from mysql.connector import Error
def mydbConnection(host_name, user_name, user_password):
connection = None
try:
connection = mysql.connector.connect(
host=host_name,
user=user_name,
passwd=user_password
)
print("Connection to MySQL DB successful")
except Error as e:
print(f"The error '{e}' occurred")
return connection
connection = mydbConnection("localhost", "root", "")
In the above script, you define a function mydbConnection() that accepts three parameters:
host_name
user_name
user_password
The mysql.connector Python SQL module contains a method .connect() that you use in line 7 to connect to a MySQL database server. Once the connection is established, the connection object is returned to the calling function. Finally, in line 18 you call mydbConnection() with the host name, username, and password.
Now, to use this connect variable, here is a function:
def mydbQuery(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
print("Database created successfully")
except Error as e:
print(f"The error '{e}' occurred")
To execute queries, you use the cursor object. The query to be executed is passed to cursor.execute() in string format.
Create a database named db for your social media app in the MySQL database server:
create_database_query = "CREATE DATABASE db"
mydbQuery(connection, create_database_query)

.cursor() gives MySQL not available

I am trying to connect to an existing MySQL database from Python and creating a table. Following is the code :
from getpass import getpass
from mysql.connector import connect, Error
def connect_db():
try:
with connect(
host="localhost",
user=input("Enter username: "),
password=getpass("Enter password: "),
database="online_movie_rating",
) as connection :
return connection
except Error as e:
print(e)
create_ratings_table_query = """
CREATE TABLE ratings (
movie_id INT,
reviewer_id INT,
rating DECIMAL(2,1),
FOREIGN KEY(movie_id) REFERENCES movies(id),
FOREIGN KEY(reviewer_id) REFERENCES reviewers(id),
PRIMARY KEY(movie_id, reviewer_id)
);
"""
cnx = connect_db()
print(cnx)
cursor = cnx.cursor()
cursor.execute(create_ratings_table_query)
cnx.commit()
When I comment the last 3 lines, I am able to print the connection object. However, when I uncomment and try to run, I get the following error :
cursor = cnx.cursor()
mysql.connector.errors.OperationalError: MySQL Connection not available.
I am on a Fedora 33 OS, Python 3.8.5 in conda environment and use VS Code as IDE. Have already pip installed the mysql-connector-python.
Can someone please help ? Have done a lot of googling but could not find a clear answer.
Thanks in advance
You have:
def connect_db():
try:
with connect(
host="localhost",
user=input("Enter username: "),
password=getpass("Enter password: "),
database="online_movie_rating",
) as connection :
return connection
except Error as e:
print(e)
But as soon as your return connection executes, the with connect(...) as connection: block terminates and the connection is closed. So you would be returning a closed connection if the connect ever succeeded. You need instead:
def connect_db():
try:
connection = connect(
host="localhost",
user=input("Enter username: "),
password=getpass("Enter password: "),
database="online_movie_rating",
)
return connection
except Error as e:
print(e)
The connection can be closed explitily with cnx.close() by the caller or it will be closed automatically when there are no more references to this connection, for example when cnx goes out of scope.
Also, if there is an error in connecting, function connect_db will return None. So perhaps the caller should check for this possibility.
The actual exception you are getting, however, is explained as:
This exception is raised for errors which are related to MySQL's operations. For example: too many connections; a host name could not be resolved; bad handshake; server is shutting down, communication errors.
You need to check your connection parameters. But clearly you must make the source changes indicated above.

Connect to postgresql using python script (database URI) but detects 'conn' as string

I am using a simple python script to connect the postgresql and future will create the table into the postgresql just using the script.
My code is:
try:
conn = "postgresql://postgres:<password>#localhost:5432/<database_name>"
print('connected')
except:
print('not connected')
conn.close()
when I run python connect.py (my file name), it throws this error :
Instance of 'str' has no 'commit' member
pretty sure is because it detects 'conn' as a string instead of database connection. I've followed this documentation (33.1.1.2) but now sure if Im doing it right. How to correct this code so it will connect the script to my postgresql server instead of just detects it as a string?
p/s: Im quite new to this.
You are trying to call a method on a string object.
Instead you should establish a connection to your db at first.
I don't know a driver which allows the use of a full connection string but you can use psycopg2 which is a common python driver for PostgreSQL.
After installing psycopg2 you can do the following to establish a connection and request your database
import psycopg2
try:
connection = psycopg2.connect(user = "yourUser",
password = "yourPassword",
host = "serverHost",
port = "serverPort",
database = "databaseName")
cursor = connection.cursor()
except (Exception, psycopg2.Error) as error :
print ("Error while connecting", error)
finally:
if(connection):
cursor.close()
connection.close()
You can follow this tutorial

Flask error when connecting to mysql using pymysql

So I am using pymysql to conenct mysql to flask. When I was developing a website on my local computer everything was fine, later when I uploaded my website to digital ocean trying to connect gives me an error:
'NoneType' object is not iterable
The view I get the error in:
#app.route('/test/')
def test_page():
try:
c, conn = connection()
return("okay")
except Exception as e:
return(str(e))
The connection file looks like this:
import pymysql
def connection():
try:
conn = pymysql.connect(host="localhost", port=3306, user="root", passwd="my_password",db="db_name",charset='utf8')
c = conn.cursor()
return conn, c
except Exception as e:
print (str(e))
I am stuck with this problem for like couple of hours, cant find a solution. Thank you in advance.
Your pymysql.connection is trying to connect to a database running on the local machine.
Evidently there is no database on your Digital Ocean server, or if there is it's not accessible on port 3306 with the credentials provided.
Found a mistake. All I need was a fresh reinstall of mysql :)

Categories