Here’s a sample Python code to write data to an SQLite database
import sqlite3 # create a connection to the 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, email TEXT)''') # insert data into the table data = [ (1, 'John Doe', '[email protected]'), (2, 'Jane Doe', '[email protected]'), (3, 'Bob Smith', '[email protected]') ] cursor.executemany('INSERT INTO users (id, name, email) VALUES (?, ?, ?)', data) # commit the changes conn.commit() # close the connection conn.close()
In this example, we first create a connection to the SQLite database by calling the connect
method of the sqlite3
module. We then create a cursor object, which we use to execute SQL commands.
Next, we create a table called users
using the CREATE TABLE
command. This table has three columns: id
, name
, and email
.
After creating the table, we insert some sample data into the table using the INSERT INTO
command. We use the executemany
method to insert multiple rows at once.
Finally, we commit the changes to the database using the commit
method, and then close the connection using the close
method.