python cx_oracle delete stmt error [duplicate] - python

This question already has an answer here:
cx_oracle Error handling issue
(1 answer)
Closed 10 years ago.
I'm trying a delete a particular row from a table in a try except block but I get the following error
self.returnvals['ERROR_CD'] = error.code
AttributeError: 'str' object has no attribute 'code'
Code:
try:
# code deleting from a table
except cx_Oracle.DatabaseError, ex:
error, = ex.args
self.conn.rollback()
self.returnerr['ID'] = 0
self.returnerr['ERROR_CD'] = error.code
self.returnerr['ERROR_MSG'] = error.message
self.returnerr['TABLE_NAME'] = self.debug_val

Your exception handling is broken. You're getting some sort of error oracle database error thrown inside your try block and it would be useful to see it, but the line in your code
self.returnerr['ERROR_CD'] = error.code
is throwing the error you're reporting because the "error" object is just a string and doesn't have a .code attribute.
Also...
delete from a table
Doesn't look like the actual DML you are attempting. Why don't you post the actual DELETE statement and maybe we can see if there's a syntax error. If this is your literal code, you need to read the documentation. I believe it's supposed to look more like:
import cx_Oracle as db
conn = db.connection()
cur = conn.cursor()
cur.execute("DELETE FROM TABLE WHERE somecolumn = someval")
conn.commit()
conn.close

Related

How is the name of these 2 errors to be invoked in Except? (Selenium and database)

I'm putting errors in Try and Except, but I'm having trouble with 2 types of errors. I'll give you an example of what I need. This except with Valure Error works fine, because I know the error is called ValueError, so:
#ONLY EXAMPLE
except ValueError:
return "FAILED"
EXCEPT ERROR N.1
The question I ask you is: how should I write for the following error? It consists of the wrong name of an html class when scraping. I wrote selenium.common.exceptions.NoSuchElementException, but the error search does not work (the script does not open at all)
except selenium.common.exceptions.NoSuchElementException:
return "FAILED"
EXCEPT ERROR N.2
Same thing for the database insert error. I want to make sure that if 0 records are saved in the database then I have an error. I tried to write like this, but it's not good:
except records_added_Results = records_added_Results = + 0:
return "FAILED"
I wrote this because I have this code for the insertion in the database. It works correctly, I am writing it just to make you understand:
con = sqlite3.connect('/home/mypc/Scrivania/folder/Database.db')
cursor = con.cursor()
records_added_Results = 0
Values = ((SerieA_text,), (SerieB_text,)
sqlite_insert_query = 'INSERT INTO ARCHIVIO_Campionati (Nome_Campionato) VALUES (?);'
count = cursor.executemany(sqlite_insert_query, Values)
con.commit()
print("Record inserted successfully ", cursor.rowcount)
records_added_Results = records_added_Results + 1
cursor.close()
How should I write? Thank you
Import the exception before you try to catch it. Add this line to your imports:
from selenium.common.exceptions import NoSuchElementException
Then you can simply do:
try:
#code that could raise the NoSuchElementException
except NoSuchElementException:
#exception handling
For the other exception, it looks like you're trying to raise an exception. Consider something like this:
if records_added_Results == 0:
raise ValueError("error message")

Getting an error when using prepared statement in python

whenever I try to run a normal query all works perfectly fine. the code executes and I can get the results but whenever I try to use a prepared statement in python I keep getting the following error:
1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? WHERE name = ?' at line 1
The code I'm trying to run:
cursor = con.db.cursor(prepared=True)
try:
cursor.execute("SELECT * FROM %s WHERE name = %s", ('operations', 'check', ))
except mysql.connector.Error as error:
print(error)
except TypeError as e:
print(e)
I've tried also to change the tuple object to string and removed one of the '%s' just for checking. but I still get an error for the '%s' synax.
another thing I've tried is to use a dict object so I've changed the '%s' to '%(table)s' and '%(name)s' and used a dict of
{'table': 'operations', 'name': 'check'}
example:
cursor.execute("SELECT * FROM %(table)s WHERE name = %(name)s", {'table': 'operations', 'name': 'check'})
but again it didn't worked and I still got the exception
am I missing something?
Thanks in advance!
-------- Edit --------
Thanks to #khelwood, I've fixed the problem.
as #khelwood mentioned in comments the problem was because I tried to use the '%s' as a parameter for table name.
python prepared statements can't handle parameters for things such as table names
so thats what throwed the exception
You can't insert a table name as a query parameter. You can pass the name you're looking for as a parameter, but it should be in a tuple: ("check",)
So
cursor.execute("SELECT * FROM operations WHERE name = %s", ("check", ))

Python/Django: how do I determine the class to specify in an "except" statement?

I am working with some Python/Django code that I inherited. In it there is a DB call surrounded by a try block, with an "except Exception ex" statement to catch all exceptions. I want to be more selective, and catch only the exception type that I anticipate. By examining the Exception object that is caught, I can tell that it's of type "DatabaseError".
The comments in my code below show the many things I have tried, based on Googling the question and searching here, along with the errors that Python gives me when I try them. Most frustrating is that I've found plenty of examples on the web of code the people say works, that looks just like what I'm trying. But the code samples I find generally don't include the "import" lines.
I suspect I need to import something more, but I can't figure out what.
import cx_Oracle
## import cx_Oracle.DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
## from cx_Oracle import DatabaseError # creates an error saying "No name 'DatabaseError in module 'cx_Oracle'"
. . .
connection = connections['ims_db']
sqlUpdateQuery = "SELECT * FROM LOCKING WHERE IDENT={0} AND KEY_ID='SL_KEY' FOR UPDATE NOWAIT".format(self.serviceUid)
cursor = connection.cursor()
try:
cursor.execute(sqlUpdateQuery)
# this gets the error "Undefined variable 'Database'"
## except Database.DatabaseError as dbe3:
# this gets the error "Undefined variable 'Oracle'"
## except Oracle.DatabaseError as dbe2:
# this gets the error "Module 'cx_Oracle' has no 'DatabaseError' member"
## except cx_Oracle.DatabaseError as dbe:
# this gets the error "Undefined variable 'DatabaseError'"
## except DatabaseError as dbe:
# this gets the error "Catching an exception which doesn't inherit from BaseException: cx_Oracle"
## except cx_Oracle as dbe:
# this gets the error "Module cx_Oracle has no '_error' member"
## except cx_Oracle._Error as dbe:
except Exception as ex:
# This gets the error "Module cx_Oracle has no 'DatabaseError' member"
## if isinstance(ex, cx_Oracle.DatabaseError) :
# This gets the error "Undefined variable 'DatabaseError'"
## if isinstance(ex, DatabaseError) :
className = type(ex).__name__
# This logs "... class = DatabaseError ..."
log.error("Exception (class = {1}) while locking service {0}".format(self.serviceUid, className))
args = ex.args
arg0=args[0]
# arg0ClassName is "_Error"
arg0ClassName = type(arg0).__name__
code = arg0.code
# codeClassName is "int"
codeClassName = type(code).__name__
msg = "Exception, code = {0}".format(code)
log.debug(msg)
raise
The correct syntax is as follows:
try:
cur.execute("some_sql_statement")
except cx_Oracle.DatabaseError as e:
error, = e.args
print("CONTEXT:", error.context)
print("MESSAGE:", error.message)
You can see that syntax in a few of the samples (like TypeHandlers.py) that you can find here: https://github.com/oracle/python-cx_Oracle/tree/master/samples.
Try running the samples and working with them to see if you can resolve your issue. If not, please create an issue containing a complete runnable sample here: https://github.com/oracle/python-cx_Oracle/issues.

How do you get isolated SQL syntax error in SQLAlchemy

Using SQLAlchemy I would like to isolate any SQL syntax errors. For instance..
try:
[row for row in db.execute(text("select * from userds"), **args)]
except ProgrammingError as error:
print(error)
I get
(psycopg2.ProgrammingError) relation "userds" does not exist
LINE 1: select * from userds
^
[SQL: 'select * from userds'] (Background on this error at: http://sqlalche.me/e/f405)
And I'm only interested in..
relation "userds" does not exist
Anyone know if this is possible?
I have found a solution to my question. You must catch StatementError and print out the orig attribute on the error object, like so..
from sqlalchemy.exc import StatementError
try:
[r for r in db.execute("invalid statement")]
except StatementError as error:
print(error.orig)
https://github.com/zzzeek/sqlalchemy/blob/699272e4dcb9aa71ebbc0d9487fb6de82d3abc2b/lib/sqlalchemy/exc.py#L280

Pandas pd.read_html error code when table does not exist

I am scraping data from websites, and searching for a table with a certain id. I have something like:
table = pd.read_html(page,attrs={'id': 'SpecificID'})[0]
The problem is that if the table with that id does not exist, my script stops with the following error message:
ValueError: No tables found
Is there a way I can catch the error code for pd.read_html? Something like:
if pd.read_html(page,attrs={'id': 'SpecificID'})[0]:
# No error
table = pd.read_html(page,attrs={'id': 'SpecificID'})[0]
else:
# Error
print("Error")
Any help would be appreciated. Thanks.
Just use a try statement:
try:
# No error
table = pd.read_html(page,attrs={'id': 'SpecificID'})[0]
except:
# Error
print("Error")

Categories