How to do Exception handling for mysql connection in python - python

I'm new to python , I want to know how to do exception handling in python in a proper way.I want to raise an exception for failure of db connection.I also don't want to include all the lines of code in try block.I want to raise connection failure exception.How to do this?
try:
conn = MySQLdb.connect(host="mysql", user="root", passwd="password"
, db="database")
mycursor = conn.cursor()
query = "INSERT INTO table1(col1,col2,col3)VALUES(%s,%s,%s)"
val = (x,y,z)
mycursor.execute(query, val)
conn.commit()
conn.close()
print("Data inserted to db")
except Exception as ex:
print(ex)

conn = MySQLdb.connect(host="mysql", user="root", passwd="password"
, db="database")
mycursor = conn.cursor()
query = "INSERT INTO table1(col1,col2,col3)VALUES(%s,%s,%s)"
try:
mycursor.execute(query, val)
except MySQLdb.Error, e:
try:
print "MySQL Error [%d]: %s" % (e.args[0], e.args[1])
return None
except IndexError:
print "MySQL Error: %s" % str(e)
return None
except TypeError, e:
print(e)
return None
except ValueError, e:
print(e)
return None
finally:
mycursor.close()
conn.close()

Something like:
connected = False
try:
conn = MySQLdb.connect(host="mysql", user="root", passwd="password"
, db="database")
connected = True
except MySQLError as ex:
print(ex)
if connected:
mycursor = conn.cursor()
query = "INSERT INTO table1(col1,col2,col3)VALUES(%s,%s,%s)"
val = (x,y,z)
mycursor.execute(query, val)
conn.commit()
conn.close()
print("Data inserted to db")

Related

What should I put for the first parameter when calling "get_Tables_byName" function?

I'm writing a python code to read from mysql database:
def create_server_connection(host, user, password):
connection = None
try:
connection = pymysql.connect(host='localhost',
user='root',
password='pwd',
database='raw_data',
cursorclass=pymysql.cursors.DictCursor)
print("MySQL Database connection successful")
except err as error:
print(f"Error: '{error}'")
return connection
def read_query(connection, query):
cur = connection.cursor()
result = None
try:
cur.execute(query)
result = cur.fetchall()
return result
except err as error:
print(f"Error: '{error}'")
return cur
def get_Tables_byName(cursor, tableName):
q1 = f'''
SELECT table_name FROM raw_data.tables
where table_name like '{tableName}'; '''
res = []
cursor.execute(q1)
for row in cursor:
res.append(row[0])
return res
get_Tables_byName(cursor,'data_31942010201')
If I want to call get_Tables_byName function, what should I put in the first parameter? If I put cursor, the error message shows NameError: name 'cursor' is not defined

Lost connection to MySQL server at 'localhost:3306', system error: Connection not available

servlet2.py
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(host='localhost',
database='*project',
user='*****',
password='*****',
)
print("Connection Established")
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print('Somethign is wrong with username or password')
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print('Database does not exist')
else:
print(e)
c = connection.cursor()
def insertSQL(user):
mySql_insert_query = "INSERT INTO python_project.test (Name) VALUES (?)", (user)
print("user:", user)
c.execute(mySql_insert_query)
print(c.rowcount, "Record inserted successfully into test table")
def username():
user = input("Please Enter Your Name: " )
insertSQL(user)
test_script.py
import servlet2
servlet2.username()
I was able to established connection to the database, however, once I enter name. It will fail to connect and prompt this error.
OperationalError: Lost connection to MySQL server at 'localhost:3306', system error: Connection not available.
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(host='127.0.0.1',
database='python_project',
user='root',
password='catdog123',
)
print("Connection Established")
#cursor = connection.cursor()
#cursor.execute("""INSERT INTO test (Name) VALUES ('harry')""")
#connection.commit()
#cursor.close()
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print('Somethign is wrong with username or password')
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print('Database does not exist')
else:
print(e)
c = connection.cursor()
def insertSQL(user):
#mySql_insert_query = """INSERT INTO test (Name) VALUES (?)""", user
print("user:", user)
print(c.rowcount, "Record inserted successfully into test table")
c.execute("""INSERT INTO test (Name) VALUES ('{}')""".format(user))
connection.commit()
def username():
user = input("Please Enter Your Name:" )
insertSQL(user)
I manage to solve it by changing the insert statement VALUES to ('{}').format(user)

I don't know why curs.execute not working

i'm studying about mysql connection with python(pycharm)
i have question about curs.execute()
when it work and when it not work...
in my code i write remarks about not working point
import pymysql
try:
conn = pymysql.connect(host='localhost', user='root', password='1234', db='university')
conn.set_charset('utf8')
curs = conn.cursor(pymysql.cursors.DictCursor) #Dictionary cursor 생성
# curs = conn.cursor()
print("Connected to MySQL")
sql = "SELECT sno, midterm, final from db_score where midterm >= 20 and final >= 20 order by sno"
# sql = "select* from db_score"
curs.execute(sql)
#this point not work :(
except Exception as e:
print(str(e))
finally:
if conn:
curs.close()
conn.close()
print("MySql connection is closed")
and fetchall() didnt work :(\
import pandas as pd
import pymysql
xl_file = 'db_score.xlsx'
df = pd.read_excel(xl_file)
tp = list(df.itertuples(index=False, name=None))
# ('sno', 'attendance', 'homework', 'discussion', 'midterm', 'final', 'score', 'grade')
try:
conn = pymysql.connect(host='localhost', user='root', password='1234', db='university')
conn.set_charset('utf8')
#curs = conn.cursor(pymysql.cursors.DictCursor)
curs = conn.cursor()
print("Connected to MySQL")
sql = "INSERT INTO db_score VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
for i in range(0, len(df.index)):
# print('hi')
curs.execute(sql, tp[i])
#why work i dont know because other part is not working
# sql2 = "SELECT* from db_score"
# curs.execute(sql2)
# try execute, but not work
records = curs.fetchall()
for row in records:
print("why didn't work")
print(row)
#print not work :(
conn.commit()
except Exception as e:
print(str(e))
conn.rollback()
finally:
if conn:
curs.close()
conn.close()
print("MySql connection is closed")
please comment why work and why not work please...
thanks for watching
db connection is so hard:(

How to add exception to python function?

Good day. I wrote an application on python that collects call logs from the Avaya PBX and writes them to the mysql database. It works well, but sometimes the PBX sends an empty string for some reason and the program fails. I attach the screen and code below. I understand that you need to wrap the function in an exception: try except, but I don’t understand how to do it. Please tell me how to do this.enter image description here
def write_db(item, *agrs):
connection = pymysql.connect(host='localhost',
user='acdr',
password='it8ejokd',
db='avaya_cdr',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
DBTBL = "cdr102019"
DBFLD = "Date_call, Time_call, `Sec_dur`, `clg_num_in_tag`, `dialed_num`, dep_called, dep_dialed"
dep_num_call = find_dep(item[3].replace(' ', ''))
name_dep_call = name_dep(dep_num_call)
dep_num_dial = find_dep(item[4].replace(' ', ''))
name_dep_dial = name_dep(dep_num_dial)
item.append(name_dep_call)
item.append(name_dep_dial)
item[1] = item[1] + "00"
try:
with connection.cursor() as cursor:
sql = "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES (%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql, (item))
connection.commit()
finally:
connection.close()
# Задаем адрес сервера
SERVER_ADDRESS = ('', 5100)
# Настраиваем сокет
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(SERVER_ADDRESS)
server_socket.listen(5)
print('server is running, please, press ctrl+c to stop')
# Слушаем запросы и пишем в db
while True:
connection, address = server_socket.accept()
data = connection.recv(1024)
if not(b'\x00\x00\x00' in data) and not(b'1370' in data):
str = data.decode("utf-8")
item=[str[0:6],str[7:11],str[12:17],str[18:33],str[34:57]]
print(item)
write_db(item)
connection.close()
You'll have to catch the exception, so we can cater for a few types, but just to be sure and get you up and running, you could do the following :)
try:
with connection.cursor() as cursor:
sql = (
"INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES "
"(%s,%s,%s,%s,%s,%s,%s)"
)
cursor.execute(
sql,
(item),
)
connection.commit()
except Exception as e:
print("Error occurred: %s"% e)
finally:
connection.close()
This should do the trick. I've used all four elements of try/except/else/finally here, with brief explanations of when they're executed.
try:
with connection.cursor() as cursor:
sql = "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES (%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql, (item))
except Exception: # If this code fails, ignore it
pass
else: # If the code inside 'try' succeeds, execute this code.
connection.commit()
finally: # Regardless of whether or not the code inside 'try' succeeds, execute this code
connection.close()

Querying results from mysql DB to a list

Eventually I would like to output the hosts to a list.
try:
cnx = mysql.connector.connect(user='root', password='passwd',
database='some_db')
cursor = cnx.cursor()
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
retrieveQuery = ("SELECT host_name,product from server")
cursor.execute(retrieveQuery)
for host,prod in cursor:
print ("{},{}".format(host,prod))
Result looks good: [host1,PowerEdge]
retrieveQuery = ("SELECT host_name from server")
cursor.execute(retrieveQuery)
for host in cursor:
print ("{}".format(host))
Result: (u'host1',)
Why am I seeing (u',) with the same code but when just one column is selected ?
Any help is much appreciated
Your cursor row result is always tuple type, try:
for row in cursor:
print ("{}".format(row.host_name))
or
for host, in cursor:
print ("{}".format(host))

Categories

Resources