import sqlite3
class City:
"""Represents a city with a name and population."""
def __init__(self, name, population):
"""Initialize the city with a name and population."""
self.name = name
self.population = population
def __str__(self):
"""Return a string representation of the city."""
return f"City: {self.name}, Population: {self.population}"
class CityDatabase:
"""Manages a database of cities."""
def __init__(self, db_name="cities.db"):
"""Initialize the database connection and create the table if necessary."""
self.db_name = db_name
self.connection = sqlite3.connect(self.db_name)
self.cursor = self.connection.cursor()
self._create_table()
def _create_table(self):
"""Create the cities table if it does not exist."""
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS cities (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
population INTEGER NOT NULL
)
""")
self.connection.commit()
def add_city(self, city):
"""Add a new city to the database."""
self.cursor.execute("INSERT INTO cities (name, population) VALUES (?, ?)", (city.name, city.population))
self.connection.commit()
def get_all_cities(self):
"""Retrieve all cities from the database."""
self.cursor.execute("SELECT name, population FROM cities")
rows = self.cursor.fetchall()
return [City(name, population) for name, population in rows]
def delete_city(self, city_name):
"""Delete a city from the database by its name."""
self.cursor.execute("DELETE FROM cities WHERE name = ?", (city_name,))
self.connection.commit()
def update_city_population(self, city_name, new_population):
"""Update the population of a city."""
self.cursor.execute("UPDATE cities SET population = ? WHERE name = ?", (new_population, city_name))
self.connection.commit()
def close(self):
"""Close the database connection."""
self.connection.close()
# Test Program
if __name__ == "__main__":
# Initialize the database
db = CityDatabase()
# Add new cities
print("Adding cities to the database...")
db.add_city(City("New York", 8419000))
db.add_city(City("Los Angeles", 3980000))
db.add_city(City("Chicago", 2716000))
# Retrieve and display all cities
print("\nCurrent cities in the database:")
for city in db.get_all_cities():
print(city)
# Update a city's population
print("\nUpdating population of Los Angeles...")
db.update_city_population("Los Angeles", 4000000)
# Retrieve and display all cities again
print("\nCities after update:")
for city in db.get_all_cities():
print(city)
# Delete a city
print("\nDeleting Chicago...")
db.delete_city("Chicago")
# Retrieve and display all cities after deletion
print("\nCities after deletion:")
for city in db.get_all_cities():
print(city)
# Close the database
db.close()
Output
Updating population of Los Angeles...
Cities after update:
City: New York, Population: 8419000
City: Los Angeles, Population: 4000000
City: Chicago, Population: 2716000