.cursor() gives MySQL not available - python

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.

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()```

PYTHON ERROR '2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (99)' while creating SQL database

Wrote a code to create a sql database via Python:
import mysql.connector
from mysql.connector import Error
def create_connection(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 = create_connection("localhost", "phpmyadmin","mhldb2022!")
But I get an error message:
The error '2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (99)' occurred
In order for the database to be created in phpMyAdmin, I installed WAMP.
Access to phpMyAdmin :
localhost/phpmyadmin/
(default login is "root", no password).
Could you help me to solve the problem?
I really can't understand what is wrong here.

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)

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

AWS Python Lambda with Oracle - OID Generation Failed

I'm trying to connect to an Oracle DB using AWS Lambda Python code.
My code is below:
import sys, os
import cx_Oracle
import traceback
def main_handler(event, context):
# Enter your database connection details here
host = "server_ip_or_name"
port = 1521
sid = "server_sid"
username = "myusername"
password = "mypassword"
try:
dsn = cx_Oracle.makedsn(host, port, sid)
print dsn
connection = cx_Oracle.Connection("%s/%s#%s" % (username, password, dsn))
cursor = connection.cursor()
cursor.execute("select 1 / 0 from dual")
except cx_Oracle.DatabaseError, exc:
error, = exc.args
print >> sys.stderr, "Oracle-Error-Code:", error.code
print >> sys.stderr, "Oracle-Error-Message:", error.message
tb = traceback.format_exc()
else:
tb = "No error"
finally:
print tb
if __name__ == "__main__":
main_handler(sys.argv[0], None)
If have already added all dependencies in "lib" folder, thanks to AWS Python Lambda with Oracle
When running this code, I'm getting:
DatabaseError: ORA-21561: OID generation failed
i've tried to connect using IP of the Oracle server and the name: same error.
Here is the output of the error
Oracle-Error-Code: 21561
Oracle-Error-Message: ORA-21561: OID generation failed
Traceback (most recent call last):
File "/var/task/main.py", line 20, in main_handler
connection = cx_Oracle.Connection("%s/%s#%s" % (username, password, dsn))
DatabaseError: ORA-21561: OID generation failed
For those who have successfully run the CX_Oracle in AWS Lambda Python, can you please help ?
Thanks
Ok, here is the explanation:
Oracle has a funny behavior where if the hostname given by hostname can't be resolved, it will fail connecting to the DB. Fortunately, in Linux, one can override the DNS entry for a session by writing an alias file in /tmp, then setting the environment variable HOSTALIASES to that file.
So adding this code to my function help to generate this file, and now I can successfully connect:
f = open('/tmp/HOSTALIASES','w')
str_host = os.uname()[1]
f.write(str_host + ' localhost\n')
f.close()
Hope it can help someone else !
See the following other question for the resolution to this problem.
sqlplus remote connection giving ORA-21561
Effectively the client requires a host name in order to generate a unique identifier which is used when connecting to the database.
The accepted solution for this correct, but please also be aware that the HOSTALIASES mechanism does require working DNS (as strange as it sounds).
I struggled with this for a few hours having implemented the accepted solution and realised that I was not permitting outbound DNS on the security group attached to by Lambda function VPC interface (my connection was by IP address to Oracle DB, so initially did not think this was required).

Categories