简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM