Thursday, February 7, 2019

Building your world - part three: reading the data in Python

Reading the data in Python

PythonAnywhere should provide you with the MySQL connector (if you are using another development environment you might need to use PIP to install it).

The following code creates a connection (you will need supply your own user name and password).

import mysql.connector
mydb = mysql.connector.connect(
  host="<yourusername>.mysql.pythonanywhere-services.com",
  user="<yourusername>",
  passwd="<mysqlpassword>",
  database="<yourusername>$adventure"
)
mycursor = mydb.cursor()

sql="SELECT * FROM rooms where roomID=%s "
roomID=("1",)

mycursor.execute(sql,roomID)

myresult = mycursor.fetchall()

for x in myresult:
  roomID=x[0]
  roomName=x[1]
  roomDescription=x[2]
print("Room ID:"+str(roomID))
print(roomName)
print(roomDescription)

This is the result of running the code.
Room ID:1KitchenA bright shiny IKEA kitchen

References: