python-mysqlHow do I insert NULL values into a MySQL table using Python?
To insert NULL values into a MySQL table using Python, you can use the MySQL Connector Python library. The following code block shows an example of how to insert a NULL value into a MySQL table using the library:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = (None, "California")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
The output of the above code will be 1 record inserted.
The code is broken down into the following parts:
- Importing the
mysql.connector
library to connect to the MySQL database. - Establishing a connection to the MySQL database.
- Creating a cursor object to execute queries and commands.
- Writing a SQL query to insert a NULL value into the customers table.
- Executing the query.
- Committing the changes to the database.
- Printing the number of records inserted.
For more information, please refer to the MySQL Connector Python documentation.
More of Python Mysql
- How can I use Python to update multiple rows in a MySQL database?
- How do I use Python to show the MySQL processlist?
- How can I use the MySQL Connector in Python?
- How do I access MySQL using Python?
- How can I use Python to retrieve data from MySQL?
- How can I connect to MySQL using Python?
- How do I use a SELECT statement in Python to query a MySQL database?
- How can I connect Python and MySQL?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
See more codes...