我对Python比较陌生,但对Java有更多的经验,所以我理解大多数概念。但是,我一直在使用MySQL和使用MySQL从一个函数传回信息以便稍后在另一个函数中使用时遇到问题。
我需要使用多个返回字段进行复杂的MySQL查询,所以我不想为每个SQL字段运行多个SQL查询,因为这会破坏数据库。下面是我想要实现的一个小例子。
我想要一个函数来运行一个从别处获取参数的SQL查询(def connectory_mysql()),然后获取SQL查询的输出并将其传递回main函数使用。然后,main函数需要对不同的参数使用SQL查询的不同列结果。
我可以返回结果并将其分配给一个打印时看起来就像字典的结果,但是如果在返回ie ldev_cap =‘ldev_ result1’之前在SQL函数中拆分使用字典中的键,则无法拆分/使用result1 = connector_mysql(subSerialNum,ldev,today_date)中的不同键或数据。但是,我似乎不能将参数传递回main函数并将它们拆分。
我一定是错过了一些简单的东西,或者不理解一些东西。任何帮助或帮助都将不胜感激。
...
result1 = connector_mysql(subSerialNum, ldev, today_date)
print(result1) #this works and appears to be a dictionary, but I can split it
## into its elements like:
ldev_cap = result1['ldev_cap'] ##-> this dosn't work here.....???? if i return it as a dictonary..
#and i'm unsure how to split them when i pass just the paramaters
#back if i split the dictionary in the sql function.
...
def connector_mysql(subSerialNum, ldev, today_date):
import pymysql.cursors
db_server = 'localhost'
db_name = 'CBDB'
db_pass = 'secure_password'
db_user = 'user1'
sql_query = (
"SELECT ldev_cap, ldev_usdcap FROM Ldevs WHERE sub_serial=%(serial)s "
"and ldev_id=%(lun)s and data_date=%(todayD)s")
connection = pymysql.connect(host=db_server,
user=db_user,
password=db_pass,
db=db_name,
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
cursor.execute(sql_query, {'serial': subSerialNum, 'lun': ldev, 'todayD': today_date})
result = cursor.fetchone()
while result:
ldev_cap = result['ldev_cap'] #here the dictionary acts as
#expected and i can assign a value
ldev_usdcap = result['ldev_usdcap']
print(result)
return ldev_cap, ldev_usdcap #here i can return
finally:
connection.close()任何帮助或帮助都将是非常重要的。
干杯格雷厄姆
发布于 2017-09-14 11:05:45
首先,您应该熟悉用于编写python代码的Python style guide。
根据您现有的代码,result1以包含(ldev_cap, ldef_usdcap)值的元组的形式返回(它不是一个目录)。您可以访问与ldev_cap的返回值相对应的result1[0]或与ldev_usdcap的返回值相对应的result1[1]的返回结果。
或者,由于要返回两个数据,因此可以使用
ldev_cap, ldev_usdcap = connector_mysql(subSerialNum, ldev, today_date)https://stackoverflow.com/questions/46209385
复制相似问题