Python SQLite - Create Table

Python SQLite - Create Table

SQLite is a C-library that provides a lightweight disk-based database. It doesn't require a separate server process or setup. The SQLite library is integrated into Python, so you can use the SQLite database without installing any additional software.

Here's how you can create a table in SQLite using Python:

1. Connect to SQLite:

Firstly, you need to connect to an SQLite database. If the database does not exist, SQLite will create it for you.

import sqlite3 # Connect to a database named 'test.db'. If it doesn't exist, it will be created. conn = sqlite3.connect('test.db') # Create a cursor object to execute SQL queries. cursor = conn.cursor() 

2. Create a Table:

Using the cursor, you can execute SQL commands. Here's how you can create a new table:

# SQL command to create a table create_table_sql = '''CREATE TABLE users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, age INTEGER );''' # Execute the SQL command using the cursor cursor.execute(create_table_sql) 

3. Commit Changes and Close:

After executing commands that modify the database, you should commit those changes. Finally, close the connection.

# Commit the changes to the database conn.commit() # Close the connection conn.close() 

Full Example:

Here's the entire process combined:

import sqlite3 # Connect to a database conn = sqlite3.connect('test.db') cursor = conn.cursor() # Create a table create_table_sql = '''CREATE TABLE users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, age INTEGER );''' cursor.execute(create_table_sql) # Commit and close conn.commit() conn.close() 

Remember:

  • Always handle exceptions when working with databases to ensure data integrity.
  • Use the with statement or manually close your connections to avoid any unintended data loss or corruption.
  • The example above uses very basic SQL. In a real-world scenario, you'd likely need to use more complex SQL statements and handle various data types and constraints appropriately.

More Tags

capitalize ioerror run-script xml-parsing firebase-console spline angular-ngselect protocol-handler android-alertdialog autofill

More Programming Guides

Other Guides

More Programming Examples