Python MySQL外键错误

时间:2015-02-19 18:52:26

标签: python mysql

我正在尝试构建一个MySQL数据库,该数据库将保存我从Google API返回的最短路径信息。

创建表格的代码如下所示。可以看出,request_no是由MySQL使用自动增量生成的。此request_no是主表的主键,它保存API请求的总体结果。 leg表,包含API请求的构成部分。 request_no必须与其各自的leg_no部分相关,如第二部分leg_data表所示。

TABLES={}
TABLES['master'] = (
    "CREATE TABLE `master` ("
    "  `request_no` int AUTO_INCREMENT,"
    "  `date_time` datetime NOT NULL,"
    "  `distance` int NOT NULL,"
    "  `duration` int NOT NULL,"
    "  `duration_in_traffic` int NOT NULL,"
    "  `Orig_lat` double NOT NULL,"
    "  `Orig_lng` double NOT NULL,"
    "  `Orig_address` longtext ,"
    "  `Dest_lat` double NOT NULL,"
    "  `Dest_lng` double NOT NULL,"
    "  `Dest_address` longtext ,"
    "  PRIMARY KEY (`request_no`)"
    ") ENGINE=InnoDB")

TABLES['leg_data'] = (
    "CREATE TABLE `leg_data` ("
    "  `leg_no` int NOT NULL AUTO_INCREMENT,"
    "  `request_no` int NOT NULL,"
    "  `leg_distance` int ,"
    "  `leg_duration` int ,"
    "  `leg_travel_mode` longtext ,"
    "  `leg_Orig_lat` double ,"
    "  `leg_Orig_lng` double ,"
    "  `leg_Dest_lat` double ,"
    "  `leg_Dest_lng` double ,"
    "  `leg_html_inst` longtext ,"
    "  `leg_polyline` longtext ,"
    "  PRIMARY KEY (`leg_no`),"
    "  CONSTRAINT `leg_data_ibfk` FOREIGN KEY (`request_no`)"
    "     REFERENCES `master` (`request_no`)"
    ") ENGINE=InnoDB") 

然后我插入从API JSON响应中解析的值。

已编辑,现在正在使用request_no: cursor.lastrowid

add_overall_data = ("INSERT INTO master" 
    "(date_time, distance, duration, duration_in_traffic, Orig_lat, Orig_lng, Orig_address, Dest_lat, Dest_lng, Dest_address)"
    "VALUES (%(date_time)s, %(distance)s, %(duration)s, %(duration_in_traffic)s, %(Orig_lat)s, %(Orig_lng)s, %(Orig_address)s, %(Dest_lat)s, %(Dest_lng)s, %(Dest_address)s)")

add_leg_data = ("INSERT INTO leg_data"
    "(request_no, leg_distance, leg_duration, leg_Orig_lat, leg_Orig_lng, leg_Dest_lat, leg_Dest_lng, leg_html_inst, leg_polyline, leg_travel_mode)" 
    "VALUES (%(request_no)s, %(leg_distance)s, %(leg_duration)s, %(leg_Orig_lat)s, %(leg_Orig_lng)s, %(leg_Dest_lat)s, %(leg_Dest_lng)s, %(leg_html_inst)s, %(leg_polyline)s, %(leg_travel_mode)s)")

for result in results:
    if result["status"] == "OK":
        for leg in result['routes'][0]['legs']:
            params = {
            "date_time": leg['_date_time'],
            "distance": leg['distance']['value'],
            "duration": leg['duration']['value'],
            "duration_in_traffic": leg['duration_in_traffic']['value'],
            "Orig_lat": leg['start_location']['lat'],
            "Orig_lng": leg['start_location']['lng'],
            "Orig_address": leg['start_address'],
            "Dest_lat": leg['end_location']['lat'],
            "Dest_lng": leg['end_location']['lng'],
            "Dest_address": leg['end_address']
            }
            cursor.execute(add_overall_data, params)
        for steps in result['routes'][0]['legs'][0]['steps']:
            params = {
            "request_no": cursor.lastrowid,
            "leg_distance": steps['distance']['value'],
            "leg_duration": steps['duration']['value'],
            "leg_Orig_lat": steps['start_location']['lat'],
            "leg_Orig_lng": steps['start_location']['lng'],
            "leg_Dest_lat": steps['end_location']['lat'],
            "leg_Dest_lng": steps['end_location']['lng'],
            "leg_html_inst": steps['html_instructions'],
            "leg_polyline": steps['polyline']['points'],
            "leg_travel_mode": steps['travel_mode']
            } 
            cursor.execute(add_leg_data, params)

我现在可以填充leg_data表中的request_no字段。虽然值不正确。什么光标。我可以使用参数将各个腿与各自的主ID(request_no)相关联吗?

1 个答案:

答案 0 :(得分:2)

写入leg_data表格时,您需要提供request_no,该request_no对应master表格for result in results: if result["status"] == "OK": for leg in result['routes'][0]['legs']: params = { "date_time": leg['_date_time'], "distance": leg['distance']['value'], "duration": leg['duration']['value'], "duration_in_traffic": leg['duration_in_traffic']['value'], "Orig_lat": leg['start_location']['lat'], "Orig_lng": leg['start_location']['lng'], "Orig_address": leg['start_address'], "Dest_lat": leg['end_location']['lat'], "Dest_lng": leg['end_location']['lng'], "Dest_address": leg['end_address'] } cursor.execute(add_overall_data, params) cursor.execute( 'SELECT request_no FROM master WHERE date_time = {}'.format( leg['_date_time'] ) ) request_no = cursor.fetchOne()[0] for steps in result['routes'][0]['legs'][0]['steps']: params = { "request_no": request_no, "leg_distance": steps['distance']['value'], "leg_duration": steps['duration']['value'], "leg_Orig_lat": steps['start_location']['lat'], "leg_Orig_lng": steps['start_location']['lng'], "leg_Dest_lat": steps['end_location']['lat'], "leg_Dest_lng": steps['end_location']['lng'], "leg_html_inst": steps['html_instructions'], "leg_polyline": steps['polyline']['points'], "leg_travel_mode": steps['travel_mode'] } cursor.execute(add_leg_data, params) 列下的值。

更新: 很遗憾' date_time'并不是唯一的,因为每秒最多可以从API接收10条记录。 下面的语法确实有效。尽管笨拙,但Orig_lat,Orig_lng,Dest_lat和Dest_lng的组合将是独一无二的。我怎么能改变' WHERE'以下声明引用上述所有4个参数?

date_time

更新2:如果cursor.execute( 'SELECT request_no FROM master WHERE col1 = {} AND col2 = {} AND ...'.format( val1, val2, ... ) ) 不足以唯一标识记录,那么您可以根据查询添加任意数量的列:

{{1}}