tiberius icon indicating copy to clipboard operation
tiberius copied to clipboard

Example of batch insert

Open cfsamson opened this issue 5 years ago • 2 comments

I'm trying to bacth insert a large number of data to the sql server, but I cant figure out a good way to do this with this driver. Do you have any pointers on how to go forward with that or where to look for information on how to accomplish this?

cfsamson avatar Feb 11 '19 11:02 cfsamson

I realized that there is no way to do this besides constructing a query yourself and insert batches of 1000 entries and repeat until finished. Maybe this issue should be converted to a feature suggestion?

cfsamson avatar Oct 21 '19 23:10 cfsamson

I'll found a pretty nice way of batch inserting which is not limited to 1000 so I'll leave it here for future reference in case it's useful for implementing a batch insert:

fn batch_insert() {
    let mut values: String = (0..10_000).map(|i| format!("({},{}),", i, i * 100)).collect();
    // Remove last comma
    values.pop();
    let update = format!("INSERT INTO sometable(id, price) SELECT id, price FROM (VALUES {})sub(id, price)", values);

    let fut = SqlConnection::connect(CONNSTR).and_then(|conn| {
        conn.simple_exec(update)
    });

    block_on_all(fut).unwrap();

}

cfsamson avatar Nov 03 '19 01:11 cfsamson