Exceptions & Errors

According to the Python DB-API errors are indicated by raising exceptions. There is one top-level exception for the DB package that is used to catch all database exceptions raised by that module. In general this package is 'module.Error'. In MySQL it is 'MySQLdb.Error'.

Every DB-API statement that you execute has the potential to raise an exception. So any time you execute a database query you should surround it with a try/exception block. This includes connections, cursor requests, and statement executions.

		# Get data from database
			cur.execute("SELECT * FROM song")
			rows = cur.fetchall()
		except MySQLdb.Error, e:
				print "MySQL Error [%d]: %s" % (e.args[0], e.args[1])
			except IndexError:
				print "MySQL Error: %s" % str(e)
		# Print results in comma delimited format
		for row in rows:
			for col in row:
				print "%s," % col
			print "\n"
<-- Home -->