Conor
Conor

Reputation: 593

MySQL from Python using MySQLdb

I am trying to add values to a MySQL database using the MySQLdb python package. Some of my columns cannot be null, and I am struggling to find a way to check what column values must be present before trying to add data to my tables. At the moment I am having to parse a file, extract a number of key, value pairs, work out which tables these should be added to, and then adding them using:

cursor.execute("""INSERT INTO %s (%s) VALUES (\"%s\")""" %(tbl, cols, vals)

I can make sure I add the columns in the correct order, and I can get the auto increment IDs to link between the different tables. What I would like to do is for each table, check whether it contains a non-nullable column, then, if necessary, modifying the input values accordingly, before then attempting to add the values to the table. Any suggestions/better ideas on how I can do this?

Upvotes: 1

Views: 61

Answers (1)

abigperson
abigperson

Reputation: 5362

You can test the INFORMATION_SCHEMA.COLUMNS table within MySQL to determine if a column accepts NULL values.

SELECT `IS_NULLABLE`
FROM INFORMATION_SCHEMA.`COLUMNS`
WHERE `TABLE_SCHEMA` = 'SchemaName'
AND `TABLE_NAME` = tbl
AND `COLUMN_NAME` = col
; # returns YES/NO

You should improve the syntax of your cursor.execute(stmt, [params]) syntax to pass in the parameter rather than hard coding it in textual sql. This will be much more reliable:

sql = "INSERT INTO %s (%s)" % (tbl, col)
sql += " VALUES(%s)"
cursor.execute(sql, [val])
connection.commit()

MySQL Docs for cursor.execute

Upvotes: 1

Related Questions