Search⌘ K
AI Features

How to Create a Database and INSERT Some Data

Explore how to create a SQLite database in Python, build tables, and insert single or multiple records safely using parameterized queries to avoid SQL injection. This lesson guides you through the basic operations of database management with Python's sqlite3 module.

We'll cover the following...

Creating a database in SQLite is really easy, but the process requires that you know a little SQL to do it. Here’s some code that will create a database to hold music albums:

Python 3.5
import sqlite3
conn = sqlite3.connect("mydatabase.db") # or use :memory: to put it in RAM
cursor = conn.cursor()
# create a table
cursor.execute("""CREATE TABLE albums
(title text, artist text, release_date text,
publisher text, media_type text)
""")
# This is SQLite's way of getting the tables created so far
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())

First we have to import the sqlite3 module and create a connection to the database. You can pass it a file path, file name or just use use the special string “:memory:” to create the ...