I'm trying to accessing Oracle from Python using cx_ORacle.
I have a select statement that returns no rows ie; NO_DATA_FOUND..and this is how Im handling the error condition.
When I execute this piece of code, the error NO_DATA_FOUND is not catched by the cx_oracle.error or cx_oracle.Databaseerror or cx_oracle.Warning..
How do I handle the NO_DATA_FOUND condition?
code.py
def DetermineNames(self):
sql = """select NAME from EMP_TAB where fd_fle_id = %s"""%(self.fileid)
try:
self.cursor.execute(sql)
result = self.cursor.fetchall()
for row in result:
print('row',row)
except cx_Oracle.Error as e:
print("Error:Unable to determine the RAW_OBJ_NAME: Object Name:%s, Function Name:%s Error:%s")%(self.__class__.__name__,sys._getframe().f_code.co_name,
str(e).strip())
except cx_Oracle.DatabaseError as e:
print("Error:Unable to determine the RAW_OBJ_NAME: Object Name:%s, Function Name:%s Error:%s")%(self.__class__.__name__,sys._getframe().f_code.co_name,
str(e).strip())
except cx_Oracle.Warning as e:
print("Error:Unable to determine the RAW_OBJ_NAME: Object Name:%s, Function Name:%s Error:%s")%(self.__class__.__name__,sys._getframe().f_code.co_name,
str(e).strip())
return self.rawname
This isn't an error condition, which is probably why none of your exceptions are being triggered. Try something like this instead:
if not self.cursor.rowcount:
print 'No rows returned'
May be use cx_Oracle._Error.code and if the value is 1403 then its a NO DATA FOUND.
....
except cx_Oracle.DatabaseError as e:
error, = e.args
if error.code == 1403:
print "No rows returned. Error Code:", error.code
....
Related
I have a list of employees and I want to create tables for them. I want to continue creating tables even if one of the table creations fail. I am using try/except block but when a table creation fails, it fails totally. I am trying below code. Appreciate your help!
employees=[1,2,3,4]
for p in employees:
create_table = f"""create table dim_{p}"""
try:
conn.execute(create_table)
print(f"success for {p}")
except Exception as e:
raise Exception(f"Failed to create table for {p} with error : {{e}}")
I think you can save the exception object for later without raising it.
employees=[1,2,3,4]
exceptions = []
for p in employees:
create_table = f"""create table dim_{p}"""
try:
conn.execute(create_table)
print(f"success for {p}")
except Exception as e:
exceptions.append((p, e)) # save info as a tuple
if exceptions: # after your loop over employees is complete
# handle your errors how you like
fail_msg = '\n'.join([f"{exception[0]} ; {exception[1]}" for exception in exceptions])
raise Exception(f"Failed to create table for the following employees:\n{fail_msg}")
When I run this (since conn is not defined via any imports) I get:
Exception: Failed to create table for the following employees:
1 ; name 'conn' is not defined
2 ; name 'conn' is not defined
3 ; name 'conn' is not defined
4 ; name 'conn' is not defined
I am using try/except block but when a table creation fails, it fails totally.
this is because you have used raise Exception(f"Failed to create table for {p} with error : {{e}}")
raising an exception, leading to the program interrupting. To avoid that, simply don't use raise.
For better understanding, look at the example below:
employees=["1","2",[1,2],"4"]
for i in employees :
try :
print(int(i))
except :
print("error on" , i)
This will output :
1
2
error on [1, 2]
4
I am trying to catch and count the duplicate entry exception :
1062 (23000): Duplicate entry '' for key 'tabale.item_UNIQUE'
Here is the code that will generate the duplicate Item exception:
stmt='INSERT INTO table.items(item) VALUES("iteratorI");'
try:
mc.execute(stmt)
conn.commit()
except pymysql.IntegrityError as e:
duplicateCounter=duplicateCounter+1
except Exception as ee:
otherErrors=otherErrors+1
I would like to be able to count duplicate item entry exceptions separately to keeping the count of other exceptions.
I want to make sure the exception that I am counting is about the duplicate entry and nothing else.
The other issue is that currently duplicateCounter is ending up being zero although I am getting at least 10 1062 exceptions which are counted in otherErrors
You haven't really stated what your concern is. Is it that you are worried that the pymysql.IntegrityError exception might be caused by something other than a duplicate key error? If that is the issue, you can check that the error code associated with the exception is 1062 (DUP_ENTRY) as follows:
stmt = 'INSERT INTO table.items(item) VALUES("iteratorI");'
try:
mc.execute(stmt)
conn.commit()
except pymysql.IntegrityError as e:
if e.args[0] == 1062:
duplicateCounter += 1
except Exception as ee:
otherErrors += 1
If you do not want to hard-code the value 1062, you could ...
from pymysql.constants.ER import DUP_ENTRY
... and then compare e.args[0] with DUP_ENTRY. But you would then be substituting one coding dependency for another.
I want to print a message in case the user made a mistake while writing the code but it doesnt work I also tried to add NameError exception, it only works if I raise an exception.Thank you for helping.
`
def cncours(nvcours,num_cours):
try :
sql="Update cours set nomC=%s where num_cours=%s"
result=cursor.fetchone()
cursor.execute(sql,(nvcours,num_cours))
print("Operation Done.")
except TypeError:
print("Plz put the name between quotes")
`
Each DB implementation (MySQL, sqlite,...) may raise their particular exceptions. So instead of catching a general exceptions, you may catch errors depending on the specific DB, then on the particular type (e.g. SyntaxError). I suggest to provoque a syntax error on your SQL statement then see what type is (e.g. errorcode or exception type) then catch it.
For instance, the MySQL connector raises error numbers:
import mysql.connector as cn
try:
#...
except cn.Error as err:
print("Something went wrong: {}".format(err))
if err.errno == errorcode.ER_BAD_TABLE_ERROR: #
Here are some MySQL Error Code Ranges
If you are using MySQLdb:
import MySQLdb
try:
#...
cursor.execute(sql)
res = cursor.fetchone()
# ...
except MySQLdb.Error, e:
print "MySQLdb.Error: {}".format(e.args)
Depending on your schema (column types) and the type from the input variable, you may use:
sql="Update cours set nomC='%s' where num_cours=%s" # Added quotes on the first replacement
Besides what you are asking, I think that the command order is inverted.
sql="Update cours set nomC=%s where num_cours=%s"
cursor.execute(sql,(nvcours,num_cours)) # First
result=cursor.fetchone() # Second
print("Operation Done.")
https://www.tutorialspoint.com/python/python_database_access.htm
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
I wrote this code to retrieve data from a cube:
rs = win32com.client.Dispatch('ADODB.RecordSet')
rs.__init__
conn = win32com.client.Dispatch('ADODB.Connection')
conn.__init__
conn.CommandTimeout=3000
conn.Open(connString)
#Retrieving data
try:
rs.Open(mdxQuery, conn, 1, 3)
except Exception as e:
print("An error occured while trying to retrieve data:")
print(str(e))
sys.exit(1)
try:
t=rs.GetRows()
except Exception as ex:
print(str(ex))
it seems the mdx query is ok, and retrieve some result (I can see it from debug mode)
but when I try to assign the result of GetRows() function to a variable, it fails, with the following message:
ADODB.Field : Either BOF or EOF is True, or the current record has been deleted. Requested operation requires a current record.
It seems to me GetRows() function is not able to handle NULL values. Is there a way to tell that method to skip NULL values or just fill it with blanks, and avoid this error?
Thanks
I'm using python with psycopg2. the following snippet produces some sort of error, but i'm not able to get any output, so i can't handle the error
cur = conn.cursor()
try:
cur.execute("INSERT INTO mqtt.records(client, id_type, value) VALUES (%(str)s, %(int)s, %(float)s)", (topic[1], switchCase(topic[-1]), msg.payload)
except psycopg2.Error as e:
print(e)
conn.commit()
cur.close()
i'm pretty sure it's some sort of typecast error, but it's not catched by the except psycopg2.Error as e:. if i'm using a general except: to catch any exceptions, it catches. but then i don't know how to get the error-message
using except Exception as e: i got the message 'arguments can't be mixed' which led me to figure that ... VALUES (%(str)s, %(int)s, %(float)s) isnt working.
instead i had to do typecasting on the (str(topic[1]), int(switchCase(topic[-1])), float(msg.payload)) part.
so i basicly missunderstood the docs. shame on me.