In Python security, how do I store results in a database?

In Python security, storing results in a database can be achieved using various libraries such as SQLite, PostgreSQL, or MySQL. Here's how you can securely store results in a database using SQLite as an example.

Keywords: Python, SQLite, database, security, SQL injection, data persistence
Description: This example demonstrates how to securely insert data into an SQLite database in Python, ensuring best practices to avoid SQL injection vulnerabilities.
import sqlite3 # Connect to the database (or create it if it doesn't exist) connection = sqlite3.connect('results.db') # Create a cursor to interact with the database cursor = connection.cursor() # Create a table if it doesn't exist cursor.execute(''' CREATE TABLE IF NOT EXISTS results ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, score INTEGER NOT NULL ) ''') # Function to insert data securely def insert_result(name, score): cursor.execute('INSERT INTO results (name, score) VALUES (?, ?)', (name, score)) connection.commit() # Example usage insert_result('Alice', 85) insert_result('Bob', 90) # Close the connection connection.close()

Keywords: Python SQLite database security SQL injection data persistence