Skip to content

Commit 3de8665

Browse files
Merge pull request #106 from pl44t/main
Sqlite Table Snippets in Python
2 parents 07d5009 + f043a9c commit 3de8665

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
---
2+
title: Query Data from Sqlite Table
3+
description: Fetches data from a specified SQLite table, with options for selecting specific columns and applying a WHERE clause.
4+
author: pl44t
5+
tags: python,sqlite,database,utility
6+
---
7+
8+
```py
9+
import sqlite3
10+
11+
def query_table(db_path, table_name, columns='*', where_clause=None):
12+
with sqlite3.connect(db_path) as conn:
13+
cursor = conn.cursor()
14+
sql = f"SELECT {columns} FROM {table_name}"
15+
if where_clause:
16+
sql += f" WHERE {where_clause}"
17+
cursor.execute(sql)
18+
return cursor.fetchall()
19+
20+
# Usage:
21+
db_path = 'example.db'
22+
table_name = 'users'
23+
columns = 'id, name, email'
24+
where_clause = 'age > 25'
25+
result = query_table(db_path, table_name, columns, where_clause)
26+
for row in result:
27+
print(row)
28+
29+
```
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
---
2+
title: Update Records in Sqlite Table
3+
description: Updates records in a specified SQLite table, allowing dynamic column updates and an optional WHERE clause.
4+
author: pl44t
5+
tags: python,sqlite,database,utility
6+
---
7+
8+
```py
9+
import sqlite3
10+
11+
def update_table(db_path, table_name, updates, where_clause=None):
12+
with sqlite3.connect(db_path) as conn:
13+
set_clause = ', '.join([f"{col} = ?" for col in updates.keys()])
14+
sql = f"UPDATE {table_name} SET {set_clause}"
15+
if where_clause:
16+
sql += f" WHERE {where_clause}"
17+
conn.execute(sql, tuple(updates.values()))
18+
conn.commit()
19+
20+
# Usage:
21+
db_path = 'example.db'
22+
table_name = 'users'
23+
updates = {'name': 'Jane Doe', 'age': 28}
24+
where_clause = "id = 1"
25+
update_table(db_path, table_name, updates, where_clause)
26+
27+
```

0 commit comments

Comments
 (0)