Inserting NULL Values into MySQL Database using Python
When working with Python scripts to insert data into MySQL, managing blank or missing values can be encountered. To resolve this issue and ensure proper insertion, consider the following solution:
Using the "None" Value
In the provided code example, it is mentioned that assigning the value "NULL" to the blank variable causes an error. To insert NULL values correctly, use the "None" value instead. The following code illustrates this:
import mysql.connector
def insert_null_value(connection, table_name, column_name, value):
cursor = connection.cursor()
if value is not None:
# If the value is not blank, insert the value
query = f"INSERT INTO {table_name} ({column_name}) VALUES (%s)"
cursor.execute(query, (value,))
else:
# If the value is blank, insert NULL
query = f"INSERT INTO {table_name} ({column_name}) VALUES (NULL)"
cursor.execute(query)
connection.commit()
cursor.close()
In this example, if the value is blank, the query to insert NULL is executed without any parameters. This approach ensures that a blank value is correctly interpreted as NULL in the database.
Additional Notes
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3