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

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)

Related

.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

How do I overcome this sql connectivity error with python?

I am not able to connect to MySQL sever using python it gives and error which says
MySQLdb._exceptions.OperationalError: (1130, "Host 'LAPTOP-0HDEGFV9' is not allowed to connect to this MySQL server")
The code I'm using:
import MySQLdb
db = MySQLdb.connect(host="LAPTOP-0HDEGFV9", # your host, usually localhost
user="root", # your username
passwd="abcd13de",
db="testing") # name of the data base
cur = db.cursor()
cur.execute("SELECT * Employee")
for row in cur.fetchall():
print(row[0])
db.close()
This is an authorization problem not a connectivity problem. Is the db running locally? If not, confirm with the admin where it is hosted. If so, try changing the host parameter to 127.0.0.1?
As described here the admin can get the hostname by running:
select ##hostname;
show variables where Variable_name like '%host%';
If the connection was timing out you could try setting the connect_timeout kwarg but that's already None by default.

Python mysqldb stops working after trying to connect to DB

I'm trying to connect to a external database but after trying to connect to the database, the whole script stops running. i'm trying to run it on a Raspberry PI 3. So after the attempt to connect to the database, it stops working. the test print does show up but the second one does not.
Script:
import MySQLdb
HOST = "host"
PORT = 3306
USER = "user"
PASS = "pass"
DATABASE = "databasename"
print("test")
db = MySQLdb.connect(HOST, USER, PASS, DATABASE)
print("test2")
cursor = db.cursor()
cursor.execute("SELECT * FROM Persoon")
data = cursor.fetchone()
print "database version :%s"% data
db.close()

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