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 INTO company (company_id,  name, employee_nums) values (%s, %s, %s) on duplicate key update company_id = values(company_id), name=values(name), employee_nums=values(employee_nums);
args = (1, "test_name", None)  # None will be convert to NULL
conn._cur.execute(sql, arg)

 

# 再次更新,%s全部不加引號,在傳值之前處理完畢

INSERT INTO company (company_id,  name, employee_nums, registered_date) 

values (%s, %s, %s, %s)

on duplicate key update company_id = values(company_id), name=values(name), employee_nums=values(employee_nums),

registered_date=values(registered_date); % (company_id, name, employee_name, "'{}'".format(registered_date) if registred_date else "NULL"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM