Skip to content

Commit f043a9c

Browse files
authored
Create update-records-sqlite-table.md
1 parent 9327f55 commit f043a9c

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
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)