Python SQLite - Connecting to Database

Python SQLite - Connecting to Database

SQLite is a lightweight, serverless, self-contained SQL database engine. To interact with SQLite databases using Python, you can use the built-in sqlite3 module.

Here's a step-by-step guide on how to connect to an SQLite database using Python:

1. Import the sqlite3 module:

import sqlite3 

2. Connect to the Database:

You can connect to an SQLite database using the connect() function. If the specified database does not exist, SQLite will create it for you.

# Connect to a database (or create one if it doesn't exist) conn = sqlite3.connect('my_database.db') 

For in-memory databases (useful for testing or temporary storage), you can use:

conn = sqlite3.connect(':memory:') 

3. Create a Cursor:

To execute SQL commands, you'll need to create a cursor object using the cursor() method of the connection object.

cursor = conn.cursor() 

4. Execute SQL Commands:

You can now use the execute() method of the cursor object to run SQL commands.

# Create a sample table cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER ) ''') 

5. Commit Changes:

After making changes (e.g., inserting, updating, or deleting records), you'll need to commit those changes to the database.

conn.commit() 

6. Close the Connection:

After you're done interacting with the database, it's a good practice to close the connection.

conn.close() 

Full Example:

Here's a consolidated example that demonstrates the steps:

import sqlite3 # Connect to database conn = sqlite3.connect('my_database.db') cursor = conn.cursor() # Create a table cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER ) ''') # Insert sample data cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("John Doe", 30)) cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("Jane Smith", 28)) # Commit changes conn.commit() # Query data cursor.execute("SELECT * FROM users") rows = cursor.fetchall() for row in rows: print(row) # Close connection conn.close() 

Using the sqlite3 module, you can easily create, read, update, and delete records in SQLite databases directly from your Python applications.


More Tags

phonegap-plugins global-variables ord cross-entropy glassfish-3 ios-app-extension strassen azureportal kotlin-android-extensions activity-indicator

More Programming Guides

Other Guides

More Programming Examples