cursor.execute('''
CREATE TABLE IF NOT EXISTS DISTRICT (
id INTEGER PRIMARY KEY,
name TEXT,
population INTEGER,
city_id INTEGER,
FOREIGN KEY(city_id) REFERENCES CITY(id)
)
''')
Create LANDMARK table
cursor.execute('''
CREATE TABLE IF NOT EXISTS LANDMARK (
id INTEGER PRIMARY KEY,
name TEXT,
type TEXT,
description TEXT,
city_id INTEGER,
FOREIGN KEY(city_id) REFERENCES CITY(id)
)
''')
Create STREET table
cursor.execute('''
CREATE TABLE IF NOT EXISTS STREET (
id INTEGER PRIMARY KEY,
name TEXT,
description TEXT,
district_id INTEGER,
FOREIGN KEY(district_id) REFERENCES DISTRICT(id)
)
''')
Create TOURIST table
cursor.execute('''
CREATE TABLE IF NOT EXISTS TOURIST (
id INTEGER PRIMARY KEY,
name TEXT,
nationality TEXT,
landmark_id INTEGER,
FOREIGN KEY(landmark_id) REFERENCES LANDMARK(id)
)
''')
Create VENDOR table
cursor.execute('''
CREATE TABLE IF NOT EXISTS VENDOR (
id INTEGER PRIMARY KEY,
name TEXT,
goodsSold TEXT,
street_id INTEGER,
FOREIGN KEY(street_id) REFERENCES STREET(id)
)
''')
Create RIVER table
cursor.execute('''
CREATE TABLE IF NOT EXISTS RIVER (
id INTEGER PRIMARY KEY,
name TEXT,
length FLOAT
)
''')
Create BRIDGE table
cursor.execute('''
CREATE TABLE IF NOT EXISTS BRIDGE (
id INTEGER PRIMARY KEY,
name TEXT,
yearBuilt INTEGER,
river_id INTEGER,
FOREIGN KEY(river_id) REFERENCES RIVER(id)
)
''')
Commit the changes and close the connection
connection.commit()
connection.close()
Assistant
To modify the Python script to print the relations between tables in a concise and clean way, you can use the following script:
import sqlite3
# Connect to the SQLite database
connection = sqlite3.connect('city_database.db')
# Create a cursor object
cursor = connection.cursor()
# List of tables and their foreign keys
table_relations = {
'CITY': {},
'DISTRICT': {'city_id': 'CITY'},
'LANDMARK': {'city_id': 'CITY'},
'STREET': {'district_id': 'DISTRICT'},
'TOURIST': {'landmark_id': 'LANDMARK'},
'VENDOR': {'street_id': 'STREET'},
'RIVER': {},
'BRIDGE': {'river_id': 'RIVER'}
}
# Function to print the relations
def print_table_relations():
for table in table_relations:
if table_relations[table]:
print(f"Table '{table}' has the following foreign keys:")
for foreign_key in table_relations[table]:
print(f"- '{foreign_key}' references '{table_relations[table][foreign_key]}'.")
else:
print(f"Table '{table}' has no foreign keys.")
# Print the table relations
print_table_relations()
# Commit the changes and close the connection
connection.commit()
connection.close()
This script defines a dictionary table_relations where each table is mapped to its foreign keys and the tables they reference. The print_table_relations function iterates over this dictionary and prints the relations in a human-readable format.