Insert NULL into MySQL

Source: Internet
Author: User

Https://stackoverflow.com/questions/36898130/python-how-to-insert-null-mysql-values

You is inserting the string ‘NULL‘ , not the NULL value. If These values is 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:

DefSqlquote(Value): "" "Naive SQL quoting all values except NULL is returned as SQL strings in single quotes, with any embedded quotes doubled . """ IfValueIs None: Return ' NULL ' Return "‘{}‘".Format(Str(value). replace ( "'" ,  "'" "sql = . ( **{k:  Sqlquote (vfor K, v in  D. ()})              

Note that because you None has to handle differently and you also has to handle proper SQL quoting! If any of the your values directly or indirectly come from user-supplied data, you ' d is open for SQL injection attacks Otherwi Se.

The above sqlquote() function should suffice for SQLite strings, which follow standard SQL quoting rules. Different databases has Different rules for this, so tripple Check your documentation.

Personally, I ' d use the SQLAlchemy library to generate SQL and has it handle quoting for you. You can configure it to produce SQL for different database engines.

Insert an empty datetime type:

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 ')
Notice the difference between the two.

In short, Python encounters none, requires a conversion process to insert ' null ' into the database, converts none to NULL, and, as the case may be, double quotation marks, without ' at%s '.

Insert NULL into MySQL

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.