简体   繁体   English

来自 Python 的 MySQL 使用 MySQLdb

[英]MySQL from Python using MySQLdb

I am trying to add values to a MySQL database using the MySQLdb python package.我正在尝试使用 MySQLdb python 包向 MySQL 数据库添加值。 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.我可以确保以正确的顺序添加列,并且我可以获取自动增量 ID 以链接不同的表。 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.您可以在 MySQL 中测试INFORMATION_SCHEMA.COLUMNS表以确定列是否接受NULL值。

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.您应该改进cursor.execute(stmt, [params])语法的语法以传递参数,而不是在文本 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 cursor.execute MySQL 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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