Quantcast
Channel: MySQL Forums - Connector/Python
Viewing all articles
Browse latest Browse all 384

MySQL Python Connector - Cursor is not connected (6 replies)

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

Viewing all articles
Browse latest Browse all 384

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>