Synax error on db.close() - python

Im trying to use mysqldb in a python script.
Here is a part of the code from the script
cursor = db.cursor()
sql = """INSERT INTO location(`name`, `lat`, `long`, `guid`, `image`, `date`)VALUES(%(name)s, %(lat)s, %(long)s, %(guid)s, %(image)s, %(date)s)"""
try:
cursor.execute(sql)
db.commit()
db.close()
Im gettig a error on the db.close()
"db.close()
^
SyntaxError: invalid syntax"
So any suggestions here?

You cannot use try without except.
The proper way to ignore all errors is this:
try:
cursor.execute(sql)
db.commit()
except:
pass
db.close()

The error is with the try: - it's looking for an except: prior to the db.close.

You would make everyone live easier if you posted fully working examples.
I added some dummy code to you post to make it run
class fake:
def commit(self,):pass
def execute(self,sql):pass
def close(self,):pass
db =fake()
cursor=fake()
if 1:
sql = """INSERT INTO location(`name`, `lat`, `long`, `guid`, `image`, `date`)VALUES(%(name)s, %(lat)s, %(long)s, %(guid)s, %(image)s, %(date)s)"""
try:
cursor.execute(sql)
db.commit()
db.close()
If I run this I get:
$ python3 test.py
File "test.py", line 17
db.close()
^
IndentationError: unexpected unindent
$
Which is show you are missing the except clause in your example.
This isn't the error you report, perhaps you Syntax Error is in part of the code you haven't included in your question.

Ignoring the indentation errors in your code, you need to use either an except clause, a finally clause, or both with your try statement.
With a finally clause you can ensure that the db connection is closed:
try:
cursor.execute(sql)
db.commit()
finally:
db.close()
In practice it is worthwhile including an except clause so that the exception can be logged:
import traceback
try:
cursor.execute(sql)
db.commit()
except Exception as exc:
traceback.print_exc() # or whatever logging you require
raise # optionally re-raise the exception
finally:
db.close() # _always_ executed

Related

How do I add logging errors in my lambda function?

I added a few, I'm not sure if any more would be useful. Also, is this all I have to do to write a lambda? I was given very little instruction on how to do it. It returns the result from the query like it's supposed to. I don't see anything wrong with it except for adding some logging exceptions?
import logging
import os
import sys
import mariadb as mdb
cnxn = mdb.connect(
user="username",
password="pass",
host="host",
port=port,
database="database"
)
cur=cnxn.cursor()
SQL_QUERY="CALL STORED_PROCEDURE();"
cur.execute(SQL_QUERY)
row=cur.fetchone()
def name_of_handler(event=None, context=None):
try:
cur.execute(SQL_QUERY)
cnxn.commit()
except mdb.Error as e:
print(f"Error: {e}")
except Exception as e:
logging.exception(e)
print(row)
cnxn.close()
name_of_handler()
UPDATE: Nevermind, how do I write a message saying "executed successfully?" I see the records did insert into the database, but there is no confirmation in the python code.

Exception occured while fetching the records near "table": syntax error In Python

Code:
import sqlite3
def create_connection(db_file):
try:
conn = sqlite3.connect("vienkarsaDB.db3")
except Exception as err:
print("Exception occured while trying to make connection", err)
else:
try:
cur=conn.cursor()
query= """SELECT * Cilvēki"""
cur.execute(query)
row=cur.fetchall()
print(row)
except Exception as err:
print("Exception occured while fetching the records", err)
else:
print("Completed")
finally:
cur.close()
finally:
conn.close()
return conn
create_connection("vienkarsaDB.db3")
Outprint:
Exception occured while fetching the records near "Cilvēki": syntax error
I want to print my SQL table row, which I have imported, row name, table name, checked, both names entered correctly. Can anybody explain why it didn't print what I wanted? Thank you!
Syntax of your query is not right. You need to use from before table name
Instead of
SELECT * Cilvēki
Please use
SELECT * from Cilvēki

Catching exception during "with" keyword opening resource

For a concrete example, take psycopg2 for Postgres(I'm aware mysql.connection has similar API):
try:
with closing(connection.cursor()) as cursor:
... # run a transaction with cursor, like insert
except IntegrityError as e:
cursor.rollback()
will the cursor be able to rollback in this case or will the cursor resource be closed before rollback occurs in this case?
Can you swap try: and with ...?
with closing(connection.cursor()) as cursor:
try:
... # run a transaction with cursor, like insert
except IntegrityError as e:
cursor.rollback()
In this way cursor will be in current scope when except ...: is reached.
With your code, when except ...: is reached, cursor will be None.

Getting error messages from psycopg2 exceptions

This is my first project using psycopg2 extensively. I'm trying to find a way to extract the psql error message for whenever a connection attempt fails. I've tested the code below will work if all the variables are set correctly, however whenever an error condition occurs (e.g. user chooses a database that doesn't exist), Python will give me the following:
I am unable to connect to the database
None
Traceback (most recent call last):
File "./duplicate_finder.py", line 163, in <module>
main(sys.argv[1:])
File "./duplicate_finder.py", line 142, in main
print e.diag.message_detail
AttributeError: 'OperationalError' object has no attribute 'diag'
Is there a simple, catch-all method to catch whatever error message psql generates when a connection fails, or do I need to write except blocks for multiple psycopg2 exceptions?
Extract from my script:
import sys, getopt, os, time, csv, psycopg2
...
...
conn_string = "host=" + dbhost + " dbname=" + database + " user=" + dbuser + " password=" + dbpass
try:
conn = psycopg2.connect(conn_string)
except psycopg2.Error as e:
print "Unable to connect!"
print e.pgerror
print e.diag.message_detail
sys.exit(1)
else:
print "Connected!"
cur = conn.cursor()
cur.execute("SELECT id, lastname, firstname, location FROM test ORDER BY ctl_upd_dttm DESC;")
print cur.fetchone()
...
conn.close()
When I try to catch exceptions, e.pgerror is always None for connection errors. The following code block gets around this by directly printing 'e'.
try:
conn = psycopg2.connect(conn_string)
except psycopg2.OperationalError as e:
print('Unable to connect!\n{0}').format(e)
sys.exit(1)
else:
print('Connected!')
# do stuff
For example, in the case of password authentication failure:
Unable to connect!
FATAL: password authentication failed for user "user"
I realize this question is a year old but hopefully might help someone in the future
Ended up here because of
class 'psycopg2.errors.InvalidCursorName'
on Django. If that's your case, be sure to makemigrations
You are catching all exceptions with the base class psycopg2.Error. Your problem is probably that the diag attribute is new in psycopg2 2.5. What is your version?
>>> print psycopg2.__version__
2.5.1 (dt dec pq3 ext)
Since Python 3.9 (.removesuffix(), f-strings) I use
except psycopg2.Error as e:
log.error(f"{type(e).__module__.removesuffix('.errors')}:{type(e).__name__}: {str(e).rstrip()}")
if conn: conn.rollback()
where log is logger.
Connection errors lives directly in psycopg2 module while syntax errors in psycopg2.errors submodule. There is an unwanted newline at the end of every psycopg2 error message.

How to avoid crashing python script when executing faulty SQL query?

I am using Python 2.7.6 and MySqldb module. I have a MySQL query that crashes sometimes. It is hard to catch the rootcause for the time being. How can I avoid crashing the python script when executing the SQL query? How can I make it fail gracefully?
The code looks like something;
cursor.execute(query)
You should throw an exception:
try:
cursor.execute(query)
except mysql.connector.Error:
"""your handling here"""
Here is a link to the MySQL Python Dev guide:
You can handle run time errors by using try except block.
At last you must use finally for cleanups like close the connection , rollback , free all the used resources etc.
Here is the example ,
import mysql.connector
try:
cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()
cursor.execute("SELECT * FORM employees") # Syntax error in query
cnx.close()
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
finally:
# cleanup (close the connection, etc...)

Categories