insert NULL into mysql
Posted Go_Forward
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了insert NULL into mysql相关的知识,希望对你有一定的参考价值。
https://stackoverflow.com/questions/36898130/python-how-to-insert-null-mysql-values
You are inserting the string ‘NULL‘
, not the NULL
value. If these values are coming from a Python structure, you need to use something else to map to the NULL
value in SQL.
You could use None
for this, and only quote other values:
def sqlquote(value):
"""Naive SQL quoting
All values except NULL are returned as SQL strings in single quotes,
with any embedded quotes doubled.
"""
if value is None:
return ‘NULL‘
return "‘{}‘".format(str(value).replace("‘", "‘‘"))
sql = "INSERT INTO test VALUES ({column1}, {column2}, {column3})".format(
**{k: sqlquote(v) for k, v in d.items()})
Note that because you have to handle None
differently, you also have to handle proper SQL quoting! If any of your values directly or indirectly come from user-supplied data, you‘d be open for SQL injection attacks otherwise.
The above sqlquote()
function should suffice for SQLite strings, which follow standard SQL quoting rules. Different databases have different rules for this, so tripple check your documentation.
Personally, I‘d use the SQLAlchemy library to generate SQL and have it handle quoting for you. You can configure it to produce SQL for different database engines.
插入空的datetime类型:
sql = "INSERT INTO test_data_table (`data`, char_test, datetime_test) VALUES (%s, %s, %s)" % (‘NULL‘, ‘NULL‘, "‘2017-09-01‘")
sql = "INSERT INTO test_data_table (`data`, char_test, datetime_test) VALUES (%s, %s, %s)" % (‘NULL‘, ‘NULL‘, ‘NULL‘)
注意两者之间的不同。
简而言之,python遇到None,需要在数据库插入‘NULL‘需要有一个转化过程,将None转为NULL,并视情况加单双引号,不加‘‘在%s.
以上是关于insert NULL into mysql的主要内容,如果未能解决你的问题,请参考以下文章
MySQL 关于表复制 insert into 语法的详细介绍
mysql insert into 或 select into - 将列从 tbl1 复制到 tbl2