Python create SQLite table

To create an SQLite table in Python, you can use the sqlite3 module, which comes with Python’s standard library. Here’s a step-by-step guide on how to do it:

Import the sqlite3 module:

import sqlite3

Establish a connection to the SQLite database or create a new one if it doesn’t exist. You can use the connect() method to do this. If the database file doesn’t exist, it will be created automatically.

conn = sqlite3.connect('mydatabase.db')

Create a cursor object using the cursor() method of the connection. The cursor will be used to execute SQL commands.

cursor = conn.cursor()

Define the SQL command to create the table. You can use the CREATE TABLE statement to specify the table’s name and columns, along with their data types and constraints. For example:

create_table_query = '''
CREATE TABLE IF NOT EXISTS mytable (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    age INTEGER
);
'''

In this example, we’re creating a table called mytable with three columns: id as an integer primary key, name as a text field (not null), and age as an integer.

Execute the SQL command to create the table using the cursor’s execute() method:

cursor.execute(create_table_query)

After executing the command, you should commit the changes to the database using the commit() method of the connection:

conn.commit()

Finally, close the cursor and the connection to release resources:

cursor.close()
conn.close()

Here’s the complete code to create an SQLite table in Python:

import sqlite3

# Establish a connection to the database (or create a new one)
conn = sqlite3.connect('mydatabase.db')

# Create a cursor
cursor = conn.cursor()

# Define the SQL command to create the table
create_table_query = '''
CREATE TABLE IF NOT EXISTS mytable (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    age INTEGER
);
'''

# Execute the SQL command to create the table
cursor.execute(create_table_query)

# Commit the changes to the database
conn.commit()

# Close the cursor and the connection
cursor.close()
conn.close()

This code will create an SQLite table called mytable with the specified columns and data types. Make sure to customize the table structure according to your requirements.