0

我使用一个函数计算服务器价格,所以我创建了一个函数,它检索服务器组件的默认价格并计算数据库中每个服务器的服务器价格,但我尝试运行此函数,但出现此错误:

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  

我不明白错误是什么,所以如果有人能帮助我,我会非常感激

4

1 回答 1

1

当您SELECT * FROM examples_calculationsmetric没有返回任何结果时,Core_prices永远不会设置(该循环中的其他变量也不会)。

Python 名称在分配给之前不存在,因此如果results是一个空列表,则for循环内的名称永远不会被分配给,因此在您稍后循环时存在。results1

您可以为这些名称设置默认值作为解决方法:

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

至少确保它们被定义。

于 2013-04-11T13:54:00.397 回答