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:
<code class="python">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()</code>
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
The above is the detailed content of How to Insert NULL Values into a MySQL Database Using Python?. For more information, please follow other related articles on the PHP Chinese website!