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.
Related
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
I have run into a very strange issue where my code below was working (I was able to add a table into the DB). After dropping a test table via the mysql workbench I am able to add a database and the code continues to run with no errors but no table is added. I have slimmed the SQL right down and attempted on different dbs. I have also restarted. Am I doing something wrong here? Any help is greatly appreciated.
import mysql.connector
import os
dirname = os.path.abspath('')
sql_filename = dirname + '\SQL_Creation\Test.sql'
class connectionsetup:
def __init__(self):
self.mydb = mysql.connector.connect(
host="localhost",
user="root",
password="")
try:
self.mycursor = self.mydb.cursor()
print('Conneciton Succesful')
self.mycursor.execute("CREATE DATABASE AP_Application_Db_test")
print('Database Created')
self.mycursor.execute('USE ap_application_db_test; Create TABLE test (SERIAL_NUMBER VARCHAR(255),VIOLATION_STATUS VARCHAR(255))', multi=True)
self.mydb.commit()
self.mydb.close()
except mysql.connector.Error as err:
print(err)
print("Error Code:", err.errno)
print("SQLSTATE", err.sqlstate)
print("Message", err.msg )
connectionsetup()
According to the docs, cursor.execute(..., multi=True)
[...] returns an iterator that enables processing the result of each statement
So the code needs to be like this:
for _ in self.mycursor.execute(multiple_sql_statements, multi=True):
pass
This is my code but I'm getting an error which says that args are not defined.
I want to know how to access data from database and also from user in GUI.
def f6():
upst.deiconify()
root.withdraw()
import cx_Oracle
con=None
cursor=None
try:
con=cx_Oracle.connect("system/abc123")
cursor=con.cursor()
sql="update student set name='%s' where rno='%d'"
args(name,rno)
cursor.execute(sql % args)
con.commit()
msg=str(cursor.rowcount)+"row updated"
messagebox.showinfo("Record updated",msg)
except cx_Oracle.DatabaseError as e:
if con is not None:
con.rollback()
messagebox.showerror("Failure",e)
finally:
cursor.close()
if con is not None:
con.close()
btnUpdate=Button(root,text="Update",width=10,command=f6)
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
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...)