【问题标题】:Get field values from mysql从mysql获取字段值
【发布时间】:2020-09-13 21:03:45
【问题描述】:

我正在尝试从 mysql 表中获取各个字段值。我正在使用 mysql 存储过程 (get_data) 和 python 游标,我可以获取整个记录,但我无法弄清楚如何获取各个字段以便将它们放入变量中。

例如,下面我想将 Smith 放入变量 last_name,将 John 放入变量 first_name,等等。

cursor = connection.cursor()
cursor.callproc('get_data', [9, ])
for result in cursor.stored_results():
print(result.fetchone()

结果:

(9, 'Smith', 'John', '', '(903) 777-5555. Box 99', 'Somewhere', 'TX', 75999 )

【问题讨论】:

    标签: python mysql


    【解决方案1】:

    将 fetchone 结果放入变量中 并使用索引来获取值

    例子

    aaa = result.fetchone()
    print(aaa[0]) # 9
    print(aaa[1]) # Smith
    
    last_name = aaa[1]
    first_name = aaa[2]
    
    print(last_name, first_name) # Smith John
    

    回复评论

    cursor = connection.cursor()
    cursor.callproc('get_data', [9, ])
    for result in cursor.stored_results():
        print(result.fetchone()) # (9, 'Smith', 'John', '', '(903) 777-5555. Box 99', 'Somewhere', 'TX', 75999 )
        no_id = result.fetchone()[0] # 9
        last_name = result.fetchone()[1] # SMith
        first_name = result.fetchone()[2] # John
        print(f"FirstName: {first_name} | LastName: {last_name}")
    

    【讨论】:

    • 感谢您的快速回复,但我收到了 - NameError: name 'result' is not defined
    • 需要在循环中定义“结果”变量。只需使用原始代码并将 print(result.fetchone()) 替换为 print(result.fetchone()[0]) 或 print(result.fetchone()[1]) 或 print(result.fetchone()[2 ])
    • 我在行中收到错误:aaa = results.fetchone() 所以不知何故我没有将 fetchone() 放入变量中。编译器无法识别结果
    【解决方案2】:

    result.fetchone() 返回元组,您可以使用其索引获取每个字段

    row = result.fetchone()
    
    row[0] #9
    row[4] #(903) 652-2038
    

    【讨论】:

    • 非常感谢。我让它变得比实际复杂得多。
    • 再次感谢您的意见。我现在的问题是,如果发送不存在的 ID,当我尝试 row = result.fetchone() 时,这当然不会返回任何代码崩溃
    • 不同的问题/范围,如果找不到答案,请研究一下,将其作为带有详细信息的问题发布,不允许在 cmets 中提出后续问题meta.stackoverflow.com/questions/321819/…,也可以stackoverflow.com/help/someone-answers跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 2021-11-07
    • 1970-01-01
    相关资源
    最近更新 更多