MySQL Python Connector - Cursor is not connected
import mysql.connector
import datetime
def connect_database():
global mydb
global mycursor
try:
if mydb.is_connected():
pass
except:
try:
print("\nCreating new db connection...")
mydb = mysql.connector.connect(host="XXX.XXX.XXX.XXX",user="XXXXXX",password="XXXXXXXXXX",database="XXXXXX", ssl_ca='ssl-client/ca.pem', ssl_cert='ssl-client/client-cert.pem', ssl_key='ssl-client/client-key.pem')
# 'buffered=True' is used to prevent unread result error
mycursor = mydb.cursor(buffered=True)
except mysql.connector.Error as q:
print("["+datetime.datetime.now().strftime("%a %b %d, %Y %I:%M:%S %p")+"] Database Error: "+str(q)+"\n")
def disconnect_database():
global mydb
global mycursor
try:
if mydb.is_connected():
mycursor.close()
mydb.close()
except:
pass
def fetch_count():
try:
connect_database()
sql="SELECT count(*) FROM status"
val=()
global mycursor
mycursor.execute(sql,val)
myresult=mycursor.fetchone()
print("\nRecord count: ", myresult[0])
except mysql.connector.Error as q:
print("["+datetime.datetime.now().strftime("%a %b %d, %Y %I:%M:%S %p")+"] Database Error: "+str(q)+"\nProcedure: fetch_count()")
def choose():
a=input("\nDo you want to re-run the query (y/n)?")
if a=='y' or a=='Y':
fetch_count()
choose()
else:
disconnect_database()
print("\nDB cursor and connection closed.")
fetch_count()
choose()
print("\nReconnecting db session after disconnection...\n")
fetch_count()
Subject
Written By
Posted
MySQL Python Connector - Cursor is not connected
November 09, 2020 04:51AM
November 10, 2020 04:24AM
November 10, 2020 09:26AM
November 10, 2020 10:37AM
November 10, 2020 11:05AM
November 10, 2020 11:01PM
November 11, 2020 09:14AM
Sorry, you can't reply to this topic. It has been closed.
Content reproduced on this site is the property of the respective copyright holders.
It is not reviewed in advance by Oracle and does not necessarily represent the opinion
of Oracle or any other party.