Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Create update-records-sqlite-table.md
  • Loading branch information
pl44t authored Jan 1, 2025
commit f043a9cc100121b796192e31b41b80dc30756c6d
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