MySQL Forums
Forum List  »  Connector/Python

MySQL Python Connector - Cursor is not connected
Posted by: Shoumik Das
Date: November 09, 2020 04:51AM

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

Options: ReplyQuote


Subject
Written By
Posted
MySQL Python Connector - Cursor is not connected
November 09, 2020 04:51AM


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.