Python SQLite – Create Table
In Python’s SQLite module, you can create tables within a database using SQL `CREATE TABLE` statements. These statements define the structure of the table, including the names and data types of its columns. Here’s how you can create a table in SQLite using Python:
1. Establish Connection: First, establish a connection to the SQLite database file using the `connect()` function from the `sqlite3` module. If the database file does not exist, SQLite will create it automatically.
2. Create Cursor: After establishing the connection, create a cursor object using the `cursor()` method. The cursor will be used to execute SQL statements.
3. Execute SQL Statement: Use the cursor’s `execute()` method to execute an SQL `CREATE TABLE` statement. This statement specifies the table name, column names, and data types for each column.
4. Commit Changes: After executing the SQL statement, commit the changes to the database using the `commit()` method of the connection object. This ensures that the changes are saved permanently.
5. Close Connection: Finally, close the cursor and connection using the `close()` method to release any resources associated with them.
Here’s an example of how to create a simple table named `employees` with three columns (`id`, `name`, and `salary`):
“`python
import sqlite3
# Establish connection to SQLite database
connection = sqlite3.connect(‘example.db’)
# Create a cursor object
cursor = connection.cursor()
# Execute SQL statement to create table
cursor.execute(”’
CREATE TABLE IF NOT EXISTS employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
salary REAL
)
”’)
# Commit changes to the database
connection.commit()
# Close cursor and connection
cursor.close()
connection.close()
“`
In this example:
– We establish a connection to an SQLite database file named `example.db`.
– We create a cursor object using the `cursor()` method.
– We execute an SQL `CREATE TABLE` statement using the cursor’s `execute()` method to create a table named `employees` with three columns (`id`, `name`, and `salary`).
– We commit the changes to the database using the `commit()` method.
– Finally, we close the cursor and connection.