2

I have a .sql script that contain all mysql queries. Now suppose after executing the script I want to check if the queries run successfully or not. In command line if we do

echo $?

Then it will return 0 if query is success and 1 if its not successful.

No I want to do it in python Script. How can this be done ?

My python script :

import mysql.connector
from mysql.connector import errorcode

try:
    cnx = mysql.connector.connect(user='myuser', password='mypass', host='127.1.2.3', database='mydb')
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
    else:
        print(err)
else:
    cursor = cnx.cursor()
    cursor.executescript("sql_queries.sql")
    cnx.close()
mat7
  • 297
  • 3
  • 11

1 Answers1

1

Are you talking about having python returning an exit code after running your script? You want to read up on sys.exit.

In your example you might have something like

except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    ...
    sys.exit(1)
else:
    cursor = cnx.cursor()
    # Might want to check whether the executescript was successful
    try:
        cursor.executescript("sql_queries.sql")
    except mysql.connector.Error as err:
        print(err)
        sys.exit(1)
    cnx.close()

Naturally, this has been asked some time ago, and other related questions:

Also do consider sending the error messages out to stderr instead of leaving the default print() to stdout, see:

Community
  • 1
  • 1
metatoaster
  • 17,419
  • 5
  • 55
  • 66
  • I want to check for a particular query in my .sql file. Say i want to check if certain insertion is made properly or not' – mat7 Jul 09 '15 at 06:50
  • See: http://stackoverflow.com/questions/9014233/how-do-i-check-if-an-insert-was-successful-with-mysqldb-in-python – metatoaster Jul 09 '15 at 06:51