一尘不染

Python MySQL连接器-使用fetchone时发现未读结果

mysql

我正在将JSON数据插入MySQL数据库

我正在解析JSON,然后使用python连接器将其插入到MySQL数据库中

通过试用,我可以看到错误与这段代码有关

for steps in result['routes'][0]['legs'][0]['steps']:
    query = ('SELECT leg_no FROM leg_data WHERE travel_mode = %s AND Orig_lat = %s AND Orig_lng = %s AND Dest_lat = %s AND Dest_lng = %s AND time_stamp = %s')
    if steps['travel_mode'] == "pub_tran":
        travel_mode = steps['travel_mode']
        Orig_lat = steps['var_1']['dep']['lat']
        Orig_lng = steps['var_1']['dep']['lng']
        Dest_lat = steps['var_1']['arr']['lat']
        Dest_lng = steps['var_1']['arr']['lng']
        time_stamp = leg['_sent_time_stamp'] 
    if steps['travel_mode'] =="a_pied":
        query = ('SELECT leg_no FROM leg_data WHERE travel_mode = %s AND Orig_lat = %s AND Orig_lng = %s AND Dest_lat = %s AND Dest_lng = %s AND time_stamp = %s')
        travel_mode = steps['travel_mode']
        Orig_lat = steps['var_2']['lat']
        Orig_lng = steps['var_2']['lng']
        Dest_lat = steps['var_2']['lat']
        Dest_lng = steps['var_2']['lng']
        time_stamp = leg['_sent_time_stamp']
    cursor.execute(query,(travel_mode, Orig_lat, Orig_lng, Dest_lat, Dest_lng, time_stamp))
    leg_no = cursor.fetchone()[0]
    print(leg_no)

我已经插入了较高级别的详细信息,现在正在搜索数据库以将此较低级别的信息与其父级关联。找到此唯一值的唯一方法是通过带有time_stamp的起点和终点坐标进行搜索。我相信逻辑是合理的,并且通过在此部分之后立即打印leg_no,我可以看到第一次检查时出现的值是正确的

但是,当添加到其余代码中时,它将导致随后的部分(使用光标插入更多数据)失败,并出现此错误-

    raise errors.InternalError("Unread result found.")
mysql.connector.errors.InternalError: Unread result found.

该问题似乎类似于Python的MySQL未读结果

查询是否太复杂并且需要拆分?还是还有其他问题?

如果查询确实太复杂了,谁能建议如何最好地将其分开?

编辑根据@Gord的帮助,Ive尝试转储所有未读的结果

cursor.execute(query,(leg_travel_mode, leg_Orig_lat, leg_Orig_lng, leg_Dest_lat, leg_Dest_lng))
            leg_no = cursor.fetchone()[0]
            try:
                cursor.fetchall()
            except mysql.connector.errors.InterfaceError as ie:
                if ie.msg == 'No result set to fetch from.':
                    pass
                else:
                    raise
            cursor.execute(query,(leg_travel_mode, leg_Orig_lat, leg_Orig_lng, leg_Dest_lat, leg_Dest_lng, time_stamp))

但是,我仍然得到

raise errors.InternalError("Unread result found.")
mysql.connector.errors.InternalError: Unread result found.
[Finished in 3.3s with exit code 1]

抓头

编辑2-当我打印ie.msg时,我得到-

No result set to fetch from

阅读 394

收藏
2020-05-17

共1个答案

一尘不染

所需要做的只是buffered将其设置为true!

cursor = cnx.cursor(buffered=True)

原因是没有缓冲的游标,结果将“延迟”加载,这意味着“
fetchone”实际上仅从查询的整个结果集中获取一行。当您再次使用同一光标时,它会抱怨您仍有n-1个结果(其中n是结果集数量)正在等待获取。但是,当您使用带缓冲的游标时,连接器会在后台获取所有行,而您只需从连接器中获取一行,这样mysql
db就不会抱怨。

2020-05-17