Python Practice › SQLite Programs › Program 2
Insert a row with parameters
Write a Python program to insert a row safely with ? placeholders.
Output
new id: 1 [(1, 'Asha', 91)]
Approach
- Pass values separately from the SQL.
Solution
import sqlite3 conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT, marks INTEGER)")cur = conn.execute("INSERT INTO students (name, marks) VALUES (?, ?)", ("Asha", 91))conn.commit()print("new id:", cur.lastrowid)print(conn.execute("SELECT * FROM students").fetchall())Output
new id: 1 [(1, 'Asha', 91)]
Learn the concept
New to this topic? Read the lesson, then come back.