2013-04-11 153 views
0

我用一个函数计算服务器的价格,所以我做这检索服务器组件的defalut价格,并计算服务器的价格在我的数据库的每台服务器exsit功能,但我尝试运行这个功能,我得到这个错误:UnboundLocalError:局部变量“Core_prices”引用之前分配

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 

我不明白什么是错误,所以如果谁能帮助我会如此感激

+1

作为一个感兴趣的问题,为什么要连接两次相同的数据库?为什么不重新使用第二个查询的第一个连接? – 2013-04-11 13:55:51

回答

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 

至少确保它们被定义。

+0

错误是因为examples_calculationsmetric表为空。该表中没有行。 它现在有效 – Imoum 2013-04-11 14:14:56

相关问题