How to know table name when inserting into two tables then triggering an exception

My Python script inserts some data into two tables, just like,

try:
    ...
    cur = conn.cursor()
    cur.execute('''insert into table_A values (%s,%s)''',(value_1,value_2))  
    cur.execute('''insert into table_B values (%s,%s,%s)''',(value_1,value_2,value_3))
    ...
except MySQLdb.Error, e:
    print "Error %d: %s" % (e.args[0], e.args[1])
    sys.exit (1)

The script has a problem: When an exception occurs (e.g.,'Error 1062: Duplicate entry') , it's hard to know 'inserting table_A' throws the exception or 'inserting table_B' throws the exception, is there a way to know the table name via MySQLdb.Error when inserting triggers an exception ?

Answers


If you want to trace the query that caused the error, make use of global variables for defining the query statement. And when an exception is raised, you can use the same variable to debug it.

Example:

globalVar = ""
try:
    ...
    cur = conn.cursor()
    globalVar = "insert into table_A values ( %s, %s )"
    cur.execute( globalVar, ( value_1, value_2 ) )  
    print "Row inserted in table_A" /* debug */

    globalVar = "insert into table_B values ( %s, %s, %s )"
    cur.execute( globalVar, ( value_1, value_2, value_3 ) )
    print "Row inserted in table_B" /* debug */

    ...
except MySQLdb.Error, e:
    print "Error %d: %s" % ( e.args[0], e.args[1] )
    print "SQL Query: %s" % globalVar /* debug in exception block */
    sys.exit (1)

As you can see the SQL Query in the log trace, you can easily figure out where and what the error is and take an action.


Need Your Help

is there a way to dynamically put a spinner next to a control instead of having divs all over the place

jquery asp.net-mvc getjson spinner

i have a number of dropdown controls and on the change event it kicks off ajax getJSON() calls. I have a div next to each dropdown with a spinner image as i want to display "loading . . " as some ...

Table with dynamic CSS class hidden via jquery call in other file

jquery css table variables

I have several tables which are generated in a foreach in reader.php

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.