Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions snippets/python/sqlite-database/query-data-from-sqlite-table.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
---
title: Query Data from Sqlite Table
description: Fetches data from a specified SQLite table, with options for selecting specific columns and applying a WHERE clause.
author: pl44t
tags: python,sqlite,database,utility
---

```py
import sqlite3

def query_table(db_path, table_name, columns='*', where_clause=None):
with sqlite3.connect(db_path) as conn:
cursor = conn.cursor()
sql = f"SELECT {columns} FROM {table_name}"
if where_clause:
sql += f" WHERE {where_clause}"
cursor.execute(sql)
return cursor.fetchall()

# Usage:
db_path = 'example.db'
table_name = 'users'
columns = 'id, name, email'
where_clause = 'age > 25'
result = query_table(db_path, table_name, columns, where_clause)
for row in result:
print(row)

```
27 changes: 27 additions & 0 deletions snippets/python/sqlite-database/update-records-sqlite-table.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
title: Update Records in Sqlite Table
description: Updates records in a specified SQLite table, allowing dynamic column updates and an optional WHERE clause.
author: pl44t
tags: python,sqlite,database,utility
---

```py
import sqlite3

def update_table(db_path, table_name, updates, where_clause=None):
with sqlite3.connect(db_path) as conn:
set_clause = ', '.join([f"{col} = ?" for col in updates.keys()])
sql = f"UPDATE {table_name} SET {set_clause}"
if where_clause:
sql += f" WHERE {where_clause}"
conn.execute(sql, tuple(updates.values()))
conn.commit()

# Usage:
db_path = 'example.db'
table_name = 'users'
updates = {'name': 'Jane Doe', 'age': 28}
where_clause = "id = 1"
update_table(db_path, table_name, updates, where_clause)

```
Loading