My program compiles but I get an ERROR when I attempt to INSERT into the SQL table. My code generates the menu but when I attempt to add a new layer I get an ERROR on Line 58 and 70. I dont know what I am doing wrong.
I tried changing the con to conn on the add_atmosphere_layer expecting the connection to work.
(FYI) I did not add my true credentials to the database part on here
import mysql.connector
from mysql.connector import Error
# Connect to my database
def create_con(hostname, username, user_password, dbname):
connection = None
try:
connection = mysql.connector.connect(
host=hostname,
user=username,
password=user_password,
database=dbname
)
print('DB connections is successful')
except Error as e:
print(f"The error {e} occurred")
return connection
def add_atmosphere_layer(cursor, conn):
try:
LayerName = input("Enter new atmosphere layer name: ") #Prompt user to enter new layer name
Altitude = float(input("Enter altitude distance in miles: ")) #Prompt user to enter new altitude
Temperature = float(input("Enter new temperature in farenheit: ")) #Prompt user to enter new temperature
ObjectsUsed = input("Enter objects used: ") #Prompt user to enter the objects used
#Insert new information into SQL table
query = "INSERT INTO LayersofAtmosphere (LAYERNAME,ALTITUDE,TEMPERATURE,OBJECTSUSED) VALUES (%s,%s,%s,%s)"
cursor.execute(query(LayerName,Altitude,Temperature,ObjectsUsed))
conn.commit()
print("Successfully added new amospheric layer")
except Error as err:
print(f"The error {err} occured")
def display_table(cursor):
cursor.execute("SELECT * FROM LayersofAtmosphere")
tablerows = cursor.fetchall()
for row in tablerows:
print(f"ID: {row[0]}, LAYERNAME: {row[1]}, ALTITUDE: {row[2]}, TEMPERATURE: {row[3]}, OBJECTSUSED: {row[4]}")
def main():
con = create_con('us-east-1.rds.amazonaws.com','admin','password','database')
if con is not None:
cursor = con.cursor()
try:
while True:
print("MENU")
print("a - Add atmosphere layers detail")
print("o - Output all atmosphere layers details in console")
print("q - Quit")
selection = input("Choose an option: ").lower()
if selection =='a':
add_atmosphere_layer (cursor.con)
elif selection == 'o':
display_table (cursor)
elif selection == 'q':
break
else:
print("Invalid selection. Please try again")
finally:
cursor.close()
con.close()
if __name__ == "__main__":
main()