from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# Create the database engine
engine = create_engine('sqlite:///overwatch.db', echo=True)

# Create a session factory
Session = sessionmaker(bind=engine)

# Define a base class for declarative models
Base = declarative_base()

# Define the Hero model
class Hero(Base):
    __tablename__ = 'heroes'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    role = Column(String)
    ultimate = Column(String)

    def __repr__(self):
        return f'<Hero(id={self.id}, name="{self.name}", role="{self.role}", ultimate="{self.ultimate}")>'

# Create the table in the database
Base.metadata.create_all(engine)
2023-03-21 12:19:36,328 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-03-21 12:19:36,336 INFO sqlalchemy.engine.Engine PRAGMA main.table_info("heroes")
2023-03-21 12:19:36,348 INFO sqlalchemy.engine.Engine [raw sql] ()
2023-03-21 12:19:36,368 INFO sqlalchemy.engine.Engine COMMIT
/var/folders/2v/jx5mc_r50sd04klb4gfy0kl00000gn/T/ipykernel_80358/388939683.py:12: MovedIn20Warning: The ``declarative_base()`` function is now available as sqlalchemy.orm.declarative_base(). (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9)
  Base = declarative_base()

Add Heroes to the Table

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# Create the database engine
engine = create_engine('sqlite:///overwatch.db', echo=True)

# Create a session factory
Session = sessionmaker(bind=engine)

# Define a base class for declarative models
Base = declarative_base()

# Define the Hero model
class Hero(Base):
    __tablename__ = 'heroes'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    role = Column(String)
    ultimate = Column(String)

    def __repr__(self):
        return f'<Hero(id={self.id}, name="{self.name}", role="{self.role}", ultimate="{self.ultimate}")>'

# Create a session to interact with the database
session = Session()

# Add some heroes to the database
mario = Hero(name='Mario', role='DPS', ultimate='Mushroom')

session.add_all([mario])
session.commit()

# Query the database for all heroes
heroes = session.query(Hero).all()
print(heroes)
/var/folders/2v/jx5mc_r50sd04klb4gfy0kl00000gn/T/ipykernel_80358/3966635573.py:12: MovedIn20Warning: The ``declarative_base()`` function is now available as sqlalchemy.orm.declarative_base(). (deprecated since: 2.0) (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9)
  Base = declarative_base()
2023-03-21 12:22:55,630 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-03-21 12:22:55,704 INFO sqlalchemy.engine.Engine INSERT INTO heroes (name, role, ultimate) VALUES (?, ?, ?)
2023-03-21 12:22:55,708 INFO sqlalchemy.engine.Engine [generated in 0.01354s] ('Mario', 'DPS', 'Mushroom')
2023-03-21 12:22:55,723 INFO sqlalchemy.engine.Engine COMMIT
2023-03-21 12:22:55,746 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-03-21 12:22:55,772 INFO sqlalchemy.engine.Engine SELECT heroes.id AS heroes_id, heroes.name AS heroes_name, heroes.role AS heroes_role, heroes.ultimate AS heroes_ultimate 
FROM heroes
2023-03-21 12:22:55,775 INFO sqlalchemy.engine.Engine [generated in 0.00291s] ()
[<Hero(id=1, name="Tracer", role="DPS", ultimate="Pulse Bomb Plus")>, <Hero(id=2, name="Mercy", role="Support", ultimate="Valkyrie")>, <Hero(id=3, name="Reinhardt", role="Tank", ultimate="Earthshatter")>, <Hero(id=4, name="Doomfist", role="Tank", ultimate="MeteorStrike")>, <Hero(id=5, name="Genji", role="DPS", ultimate="DragonBlade")>, <Hero(id=6, name="Ashe", role="DPS", ultimate="Bob")>, <Hero(id=7, name="Mario", role="DPS", ultimate="Mushroom")>]

DELETE

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# Create the database engine
engine = create_engine('sqlite:///overwatch.db', echo=True)

# Create a session factory
Session = sessionmaker(bind=engine)

# Define a base class for declarative models
Base = declarative_base()

# Define the Hero model
class Hero(Base):
    __tablename__ = 'heroes'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    role = Column(String)
    ultimate = Column(String)

    def __repr__(self):
        return f'<Hero(id={self.id}, name="{self.name}", role="{self.role}", ultimate="{self.ultimate}")>'

# Create a session to interact with the database
session = Session()

# Query the database for the hero to delete
hero_to_delete = session.query(Hero).filter_by(name='Mercy').first()

# Delete the hero object from the session and commit the changes to the database
session.delete(hero_to_delete)
session.commit()

# Query the database for all heroes
heroes = session.query(Hero).all()
print(heroes)
2023-03-21 08:55:19,861 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-03-21 08:55:19,881 INFO sqlalchemy.engine.Engine SELECT heroes.id AS heroes_id, heroes.name AS heroes_name, heroes.role AS heroes_role, heroes.ultimate AS heroes_ultimate 
FROM heroes 
WHERE heroes.name = ?
 LIMIT ? OFFSET ?
2023-03-21 08:55:19,886 INFO sqlalchemy.engine.Engine [generated in 0.00538s] ('Mercy', 1, 0)
2023-03-21 08:55:19,901 INFO sqlalchemy.engine.Engine DELETE FROM heroes WHERE heroes.id = ?
2023-03-21 08:55:19,903 INFO sqlalchemy.engine.Engine [generated in 0.00193s] (2,)
2023-03-21 08:55:19,907 INFO sqlalchemy.engine.Engine COMMIT
2023-03-21 08:55:19,919 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-03-21 08:55:19,921 INFO sqlalchemy.engine.Engine SELECT heroes.id AS heroes_id, heroes.name AS heroes_name, heroes.role AS heroes_role, heroes.ultimate AS heroes_ultimate 
FROM heroes
2023-03-21 08:55:19,927 INFO sqlalchemy.engine.Engine [generated in 0.00560s] ()
[<Hero(id=3, name="Reinhardt", role="Tank", ultimate="Earthshatter")>, <Hero(id=4, name="Tracer", role="DPS", ultimate="Pulse Bomb")>, <Hero(id=5, name="Mercy", role="Support", ultimate="Valkyrie")>, <Hero(id=6, name="Reinhardt", role="Tank", ultimate="Earthshatter")>, <Hero(id=7, name="Tracer", role="DPS", ultimate="Pulse Bomb")>, <Hero(id=8, name="Mercy", role="Support", ultimate="Valkyrie")>, <Hero(id=9, name="Reinhardt", role="Tank", ultimate="Earthshatter")>, <Hero(id=10, name="Tracer", role="DPS", ultimate="Pulse Bomb")>, <Hero(id=11, name="Mercy", role="Support", ultimate="Valkyrie")>, <Hero(id=12, name="Reinhardt", role="Tank", ultimate="Earthshatter")>, <Hero(id=13, name="Doomfist", role="Tank", ultimate="MeteorStrike")>, <Hero(id=14, name="Tracer", role="DPS", ultimate="Pulse Bomb")>, <Hero(id=15, name="Mercy", role="Support", ultimate="Valkyrie")>, <Hero(id=16, name="Reinhardt", role="Tank", ultimate="Earthshatter")>, <Hero(id=17, name="Doomfist", role="Tank", ultimate="MeteorStrike")>, <Hero(id=18, name="Tracer", role="DPS", ultimate="Pulse Bomb")>, <Hero(id=19, name="Mercy", role="Support", ultimate="Valkyrie")>, <Hero(id=20, name="Reinhardt", role="Tank", ultimate="Earthshatter")>, <Hero(id=21, name="Doomfist", role="Tank", ultimate="MeteorStrike")>]

Clear Database

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# Create the database engine
engine = create_engine('sqlite:///overwatch.db', echo=True)

# Create a session factory
Session = sessionmaker(bind=engine)

# Define a base class for declarative models
Base = declarative_base()

# Define the Hero model
class Hero(Base):
    __tablename__ = 'heroes'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    role = Column(String)
    ultimate = Column(String)

    def __repr__(self):
        return f'<Hero(id={self.id}, name="{self.name}", role="{self.role}", ultimate="{self.ultimate}")>'

# Create a session to interact with the database
session = Session()

# Delete all heroes from the database
session.query(Hero).delete()
session.commit()

# Query the database for all heroes (should be empty)
heroes = session.query(Hero).all()
print(heroes)
2023-03-21 08:58:05,530 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-03-21 08:58:05,539 INFO sqlalchemy.engine.Engine DELETE FROM heroes
2023-03-21 08:58:05,546 INFO sqlalchemy.engine.Engine [generated in 0.00616s] ()
2023-03-21 08:58:05,551 INFO sqlalchemy.engine.Engine COMMIT
2023-03-21 08:58:05,561 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-03-21 08:58:05,568 INFO sqlalchemy.engine.Engine SELECT heroes.id AS heroes_id, heroes.name AS heroes_name, heroes.role AS heroes_role, heroes.ultimate AS heroes_ultimate 
FROM heroes
2023-03-21 08:58:05,592 INFO sqlalchemy.engine.Engine [generated in 0.02413s] ()
[]

Update

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# Create the database engine
engine = create_engine('sqlite:///overwatch.db', echo=True)

# Create a session factory
Session = sessionmaker(bind=engine)

# Define a base class for declarative models
Base = declarative_base()

# Define the Hero model
class Hero(Base):
    __tablename__ = 'heroes'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    role = Column(String)
    ultimate = Column(String)

    def __repr__(self):
        return f'<Hero(id={self.id}, name="{self.name}", role="{self.role}", ultimate="{self.ultimate}")>'

# Create a session to interact with the database
session = Session()

# Query for a hero to update
hero = session.query(Hero).filter_by(name='Tracer').first()

# Update the hero's ultimate ability
hero.ultimate = 'Pulse Bomb Plus'

# Commit the changes to the database
session.commit()

# Query the database for the updated hero
hero = session.query(Hero).filter_by(name='Tracer').first()
print(hero)
2023-03-21 09:05:39,581 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-03-21 09:05:39,589 INFO sqlalchemy.engine.Engine SELECT heroes.id AS heroes_id, heroes.name AS heroes_name, heroes.role AS heroes_role, heroes.ultimate AS heroes_ultimate 
FROM heroes 
WHERE heroes.name = ?
 LIMIT ? OFFSET ?
2023-03-21 09:05:39,590 INFO sqlalchemy.engine.Engine [generated in 0.00148s] ('Tracer', 1, 0)
2023-03-21 09:05:39,609 INFO sqlalchemy.engine.Engine UPDATE heroes SET ultimate=? WHERE heroes.id = ?
2023-03-21 09:05:39,610 INFO sqlalchemy.engine.Engine [generated in 0.00110s] ('Pulse Bomb Plus', 1)
2023-03-21 09:05:39,614 INFO sqlalchemy.engine.Engine COMMIT
2023-03-21 09:05:39,617 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2023-03-21 09:05:39,619 INFO sqlalchemy.engine.Engine SELECT heroes.id AS heroes_id, heroes.name AS heroes_name, heroes.role AS heroes_role, heroes.ultimate AS heroes_ultimate 
FROM heroes 
WHERE heroes.name = ?
 LIMIT ? OFFSET ?
2023-03-21 09:05:39,620 INFO sqlalchemy.engine.Engine [cached since 0.03102s ago] ('Tracer', 1, 0)
<Hero(id=1, name="Tracer", role="DPS", ultimate="Pulse Bomb Plus")>

Alt text

Alt text

import sqlite3

# create a connection to the database file
conn = sqlite3.connect('overwatch2.db')

# create a new table called 'heroes'
conn.execute('''CREATE TABLE IF NOT EXISTS heroes
             (id INTEGER PRIMARY KEY AUTOINCREMENT,
              name TEXT,
              role TEXT,
              ultimate_ability TEXT);''')

# insert a new hero into the table
conn.execute("INSERT INTO heroes (name, role, ultimate_ability) VALUES ('Tracer', 'Damage', 'Pulse Bomb')")

# save the changes and close the connection
conn.commit()
conn.close()
conn = sqlite3.connect('overwatch2.db')

# insert a new hero into the table
conn.execute("INSERT INTO heroes (name, role, ultimate_ability) VALUES ('Tracer', 'Damage', 'Pulse Bomb')")

# save the changes and close the connection
conn.commit()
conn.close()
import sqlite3

def create_hero():
    hero_name = input("Enter new hero name:")
    role = input("Enter new hero role:")
    ultimate_ability = input("Enter ultimate ability name:")
    
    # Connect to the database file
    conn = sqlite3.connect("overwatch2.db")

    # Create a cursor object to execute SQL commands
    cursor = conn.cursor()

    try:
        # Execute an SQL command to insert data into a table
        cursor.execute("INSERT INTO heroes (name, role, ultimate_ability) VALUES (?, ?, ?)", (hero_name, role, ultimate_ability))
        
        # Commit the changes to the database
        conn.commit()
        print(f"A new hero {hero_name} has been created")
                
    except sqlite3.Error as error:
        print("Error while executing the INSERT:", error)


    # Close the cursor and connection objects
    cursor.close()
    conn.close()
    
create_hero()
A new hero genji has been created
import sqlite3

def read():
    # Connect to the database file
    conn = sqlite3.connect('overwatch2.db')

    # Create a cursor object to execute SQL commands
    cursor = conn.cursor()

    try:
        # Execute an SQL command to select all data from the "heroes" table
        cursor.execute("SELECT * FROM heroes")
        
        # Fetch all the rows returned by the SQL command
        rows = cursor.fetchall()
        
        # Print the data
        for row in rows:
            print(row)
                
    except sqlite3.Error as error:
        print("Error while executing the SELECT:", error)


    # Close the cursor and connection objects
    cursor.close()
    conn.close()
import sqlite3

def update_hero(tracer):
    # Prompt the user to enter the hero ID and new information
    hero_id = input("Enter the ID of the hero you want to update: ")
    hero_name = input("Enter the new hero name (leave blank to keep current name): ")
    role = input("Enter the new role (leave blank to keep current role): ")
    ultimate_ability = input("Enter the new ultimate ability (leave blank to keep current ability): ")

    # Connect to the database
    conn = sqlite3.connect('overwatch2.db')

    # Create a cursor object
    cursor = conn.cursor()

    # Build the SQL query
    sql = "UPDATE heroes SET"
    params = []

    # If the user entered a new hero name, add it to the query and parameters
    if hero_name:
        sql += " hero_name = ?,"
        params.append(hero_name)

    # If the user entered a new role, add it to the query and parameters
    if role:
        sql += " role = ?,"
        params.append(role)

    # If the user entered a new ultimate ability, add it to the query and parameters
    if ultimate_ability:
        sql += " ultimate_ability = ?,"
        params.append(ultimate_ability)

    # Remove the trailing comma from the query
    sql = sql.rstrip(",")

    # Add the WHERE clause to specify the hero to update
    sql += " WHERE id = ?"
    params.append(hero_id)

    # Execute the SQL query with the provided parameters
    cursor.execute(sql, params)

    # Commit the changes and close the connection
    conn.commit()
    conn.close()

    # Display a message indicating success
    print("Hero updated successfully!")
update_hero('Tracer', 'Damage', 'Pulse Bomb Plus')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/Users/jaggerklein/vscode/The-Pentagon/_notebooks/2023-3-19-2.4hacks.ipynb Cell 19 in <cell line: 1>()
----> <a href='vscode-notebook-cell:/Users/jaggerklein/vscode/The-Pentagon/_notebooks/2023-3-19-2.4hacks.ipynb#X36sZmlsZQ%3D%3D?line=0'>1</a> update_hero('Tracer', 'Damage', 'Pulse Bomb Plus')

TypeError: update_hero() takes 0 positional arguments but 3 were given
import sqlite3

def delete_hero():
    # Prompt the user for the hero name to delete
    name = input("tracer")

    # Connect to the database file
    conn = sqlite3.connect("overwatch2.db")

    # Create a cursor object to execute SQL commands
    cursor = conn.cursor()

    try:
        # Execute an SQL command to delete the hero with the given name
        cursor.execute("DELETE FROM heroes WHERE hero_name = ?", (name))

        # Check if any rows were affected by the delete command
        if cursor.rowcount == 0:
            print(f"No hero with name {name} found.")
        else:
            print(f"{cursor.rowcount} hero(s) with name {name} deleted.")

        # Commit the changes to the database
        conn.commit()

    except sqlite3.Error as error:
        print("Error while executing the DELETE:", error)

    # Close the cursor and connection objects
    cursor.close()
    conn.close()