diff --git a/snippets/python/sqlite-database/query-data-from-sqlite-table.md b/snippets/python/sqlite-database/query-data-from-sqlite-table.md new file mode 100644 index 00000000..95e4abab --- /dev/null +++ b/snippets/python/sqlite-database/query-data-from-sqlite-table.md @@ -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) + +``` diff --git a/snippets/python/sqlite-database/update-records-sqlite-table.md b/snippets/python/sqlite-database/update-records-sqlite-table.md new file mode 100644 index 00000000..14104c8f --- /dev/null +++ b/snippets/python/sqlite-database/update-records-sqlite-table.md @@ -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) + +```