如何插入列表mariadb,其中多个值是预期的,只有列表给出

f0ofjuux  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(169)

我想用python在mariadb中插入一个列表(批量插入)。但是这个插入有5个参数,我只想把列表作为一个参数。如果你读了代码,这是有意义的。如果我试图在第一个代码块中只插入event_list,我会得到以下错误:

mariadb.ProgrammingError: statement (5) doesn't match the number of data elements (23305).

下面的代码是我想要的代码(但它不工作)

@classmethod
def insert_data(cls, event_list):
    """Adds events to the database

    Args:
        events ([string]): Name of events
        :param event_list: list of events
    """

    try:
        DB.create(
            f"INSERT INTO Events(road_name, avg_speed, flow_count, ts_event, uuid)  VALUES (?, ?, ?, ?, ?)",
            event_list)
    except Error:
        return Error

event_list包含所有事件
event_list中的值示例:
(“A2”、“84”、“13”、“2022年12月06日10:34:12.867Z”、“e9 af 9383 - 2d 7 f-4963- 88 c9 - 38 aa 1d 9 c33 cc”)
事件中也可以有“无”类型(我认为这与此问题无关)
(“A9”、无、无、“2022年12月6日10:34:14.436Z”、“49 c10 cd 1 -3029-4367-a557- 010 d5 eb 1334 a”)
使用当前的insert语句,它会逐个插入每一行,这需要很长时间(因此采用了批量插入的思想)。下面的代码是我现在的代码,它对每一行都进行插入,而不是一次插入所有行。

@classmethod
def insert_data(cls, road_name, avg_speed, flow_count, ts_event, uuid):
    """Adds events to the database

    Args:
        events ([string]): Name of events
        :param road_name:
        :param avg_speed:
        :param flow_count:
        :param ts_event:
        :param uuid:
    """
    db_values = (road_name, avg_speed, flow_count, ts_event, uuid)
    try:
        DB.create(
            'INSERT INTO Events(road_name, avg_speed, flow_count, ts_event, uuid)  VALUES(?, ?, ?, ?, ?)',
            db_values)
    except Error:
        print(Error)

此函数用于添加数据库中的所有事件:

@classmethod
def add_all_events(cls):
    # combined_events = DataEndpointFetcher.combine_matching_events()
    with open('../refactored_ndw_data.json') as json_file:
        combined_events = json.load(json_file)
    event_list = list()
    for event in tqdm(combined_events['events']):
        try:
            road_name = event['lanelocation']['road']

            avg_speed = event["avgspeed"].get("kmph")

            flow_count = event["flow"].get("count")

            ts_event = event['ts_event']

            uuid = event['measuring_point_id'].get("uuid")
        except:
            continue

        event_list.append((road_name, avg_speed, flow_count, ts_event, uuid))
    EventModel.insert_data(event_list)

所以我的问题是:如何仅使用作为VALUES参数的列表进行INSERT。

ni65a41a

ni65a41a1#

您可以使用Python的{} paramstyle作为:

DB.create(
  'INSERT INTO EVENTS(road_name, avg_speed, flow_count, ts_event, uuid) VALUES{}'.format(db_values)
)

您创建的db_values是一个可以索引的元组,5?需要传递5个变量。

DB.create(
  'INSERT INTO Events(road_name, avg_speed, flow_count, ts_event, uuid) VALUES(?, ?, ?, ?, ?)', db_values[0], db_values[1], db_values[2], db_values[3], db_values[4]
)

相关问题