To insert NULL values into a SQLite database using Python, you can utilize the parameter substitution technique provided by the SQLite3 module.
First, you need to establish a connection with the SQLite database using the connect()
function.
Then, create a cursor object using the cursor()
method to execute SQL queries on the database.
Here’s an example that demonstrates inserting NULL values into a SQLite database using Python:
import sqlite3 # Establish a connection to the SQLite database conn = sqlite3.connect('example.db') # Create a cursor object cursor = conn.cursor() # Create a table cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)") # Insert NULL values into the table cursor.execute("INSERT INTO users VALUES (1, 'John Doe', NULL)") cursor.execute("INSERT INTO users (id, name) VALUES (2, 'Jane Smith')") # Commit the changes and close the connection conn.commit() conn.close()
In this example, we create a table called “users” with three columns: “id” (integer, primary key), “name” (text), and “age” (integer).
We use the “NULL” keyword to represent a missing or unknown value for the “age” column in the first insert statement.
In the second insert statement, we only specify values for the “id” and “name” columns, leaving the “age” column as NULL by default.
After executing the insert statements, we need to commit the changes using the commit()
method.
Finally, we close the connection to the database using the close()
method.