[python]Create sqlite3 database

Total five steps

  • Connect to a database file
  • Create a cursor object
  • Execute the create table query
  • Commit the execution
  • Close the database

Example I want to create a users table with three columns: id, username, password

import sqlite3

# step 1: Connect to a db file, if the db file does not exist, sqlite3 will create one.
connection = sqlite3.connect("data.db")
# step 2: Create a cursor object, this cursor is a pointer of a table and execute query.
cursor = connection.cursor()
create_user_table = "CREATE TABLE IF NOT EXISTS users (id Integer PRIMARY KEY," \
                    "username text," \
                    "password text)"
# step 3: Execute sql query to create a table users, if the table exists nothing will be done.
# step 4: Commit the change.
# step 5: close the database.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s