Thursday, February 7, 2019

Building your world - part four: the Room class

The Room class

The Room class as developed on the course has a creator that takes room name because they are being created from scratch. However for this project, the room name and description exist on the database. This means the creator(__init__) will take a room ID and a database cursor as parameters.
  
class Room():
    def __init__(self,room_id,acursor):
        sql="SELECT * FROM rooms where roomID=%s "
        roomID=(str(room_id),)

        acursor.execute(sql,roomID)

        myresult = acursor.fetchall()

        for x in myresult:
            self.roomID=x[0]
            self.name=x[1]
            self.description=x[2]

    # Getters and Setters

    def get_description(self):
        return self.description

    def get_name(self):
        return self.name

    def get_details(self):
        print(self.get_name())
        print("======")
        print(self.get_description())




Here is the test code (testroom.py)

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



aroom=Room(1,mycursor)
print(aroom.get_details())

Kitchen======A bright shiny IKEA kitchenNone