0

i use a function calculate servers prices so i made a function which retrieve a defalut prices of a server components and calculate server price for each server exsit in my DB but i try to run this function, i get this error:

function.py

import MySQLdb

def calculations_metric (param) :
    db = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
    cursor = db.cursor()
    sql = "SELECT * FROM examples_calculationsmetric"
    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
        RAM_prices = int(row[1])
        Core_prices = int(row[2])
        HHD_SATA_prices =int(row[3])
        HHD_SSD_prices =int(row[4])
        CPU_priority = int(row[5])
        Avaibility = int(row[6])
    db.close()

    db1 = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
    cursor1 = db1.cursor()
    sql1 = "SELECT * FROM examples_servercomponents WHERE id ='%d'" %(param)
    cursor1.execute(sql1)
    results1 = cursor1.fetchall()
    for row in results1:
        if row[6] == 'SATA':
            Core_price = int(row[2]) * Core_prices # the error is here
            Priority_price = int(row[3]) * CPU_priority
            RAM_price = int(row[4]) * RAM_prices
            HDD_price = int(row[5]) * HHD_SATA_prices
            Availibility_price = int(row[7])*Avaibility

        elif row[6] == 'SSD':
            Core_price = int(row[2]) * Core_prices
            Priority_price = int(row[3]) * CPU_priority
            RAM_price = int(row[4]) * RAM_prices
            HDD_price = int(row[5]) * HHD_SSD_prices
            Availibility_price = int(row[7])*Avaibility

    price = Core_price + Priority_price + RAM_price + HDD_price + Availibility_price
    db1.close()
    return price  

i don't get what is the error so if can anyone help i will be so greatful

Imoum
  • 745
  • 3
  • 12
  • 24
  • 1
    Why are you connecting to the same database twice, as a matter of interest? Why not just *reuse* the first connection for the second query? – Martijn Pieters Apr 11 '13 at 13:55

1 Answers1

1

When your SELECT * FROM examples_calculationsmetric doesn't return any results, Core_prices is never set (nor are the other variables in that loop).

Python names do not exist until assigned to, so if results is an empty list, the names inside the for loop never get assigned to and thus do not exist by the time you loop over results1 later on.

You could set default values for those names as a work-around:

RAM_prices = 0
Core_prices = 0
HHD_SATA_prices = 0
HHD_SSD_prices = 0
CPU_priority = 0
Avaibility = 0

to at least ensure that they are defined.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • the error was because examples_calculationsmetric Table was empty. there is no line in that table. it works now – Imoum Apr 11 '13 at 14:14