开发者

How to INSERT list mariadb where multiple values are excpected only list given

I want to insert a list (bulk insert) into mariadb using python. However the insert has 5 arguments and I only want to give the list as an argument. It will make sense if you read the code:

@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

The event_list contains all the events

An example of the values in event_list:

('A2', '84', '13', '2022-12-06T10:34:12.867Z', 'e9af9383-2d7f-4963-88c9-38aa1d9c33cc')

There can also be a None type in an event (I don't think that matters at all with this issue)

('A9', None, None, '2022-12-06T10:34:14.436Z', '49c10cd1-3029-4367-a557-010d5eb1334a')

with the current insert statement it inserts every row one by one which takes a long time(therefore the bulk insert idea)

@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_nam开发者_Go百科e, avg_speed, flow_count, ts_event, uuid)  VALUES(?, ?, ?, ?, ?)',
            db_values)
    except Error:
        print(Error)

If I try to insert only the event_list with the first block of code I get the following error:

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

So my question: How do I INSERT with only the list given as an argument for VALUES.


db_values as you created is a tuple which can be indexed, and 5 ?'s requires 5 variables to be passed.

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]
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜