Skip to content

Commit 9327f55

Browse files
authored
Create query-data-from-sqlite-table.md
1 parent e9ee067 commit 9327f55

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-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+
```

0 commit comments

Comments
 (0)