0% found this document useful (0 votes)
2 views

Database

The document contains Python code for managing a SQLite database with functions to connect to the database, create a table, insert, retrieve, update, and delete records. It defines a 'records' table with fields for id, name, and age. The script ensures the table is created if it does not already exist.

Uploaded by

madjie7071
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Database

The document contains Python code for managing a SQLite database with functions to connect to the database, create a table, insert, retrieve, update, and delete records. It defines a 'records' table with fields for id, name, and age. The script ensures the table is created if it does not already exist.

Uploaded by

madjie7071
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import sqlite3

def connect_db():
return sqlite3.connect('app.db')

def create_table():
with connect_db() as conn:
conn.execute('''CREATE TABLE IF NOT EXISTS records
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER NOT NULL);''')
conn.commit()

def insert_record(name, age):


with connect_db() as conn:
conn.execute('INSERT INTO records (name, age) VALUES (?, ?)', (name, age))
conn.commit()

def get_records():
with connect_db() as conn:
cursor = conn.execute('SELECT id, name, age FROM records')
return cursor.fetchall()

def update_record(record_id, name, age):


with connect_db() as conn:
conn.execute('UPDATE records SET name = ?, age = ? WHERE id = ?', (name,
age, record_id))
conn.commit()

def delete_record(record_id):
with connect_db() as conn:
conn.execute('DELETE FROM records WHERE id = ?', (record_id,))
conn.commit()

# Create table if not exists


create_table()

You might also like