Create single item parentheses strings for SQL Insert statement in Python

Question:

I have a list of integers but would like to turn them into single-item tuples for a SQL statement. I am struggling at trying to get integers into single tuple-like structures within a large string.

The ideal goal is to generate a chunk_size of queries following this format below. So ideally I’d want to end up with an iterable of insert statements which have a chunk_size of x values being inserted in each statement.

# The list of integers is like the following
# Approximate size n = 1M+
li: list[int] = [0,1,2,3,4,5,6]

Desired result:

# I'd like to have an iterable of statements like this (of a certain chunk_size (x) specified by the user)
queries: list[str] = [
    'insert into test_table (test_col) values (0),   (1),   (2),   (3),  (4)...   (x)',
    ...
    'insert into test_table (test_col) values (x+1), (x+2), (x+3), (x+4) (x+5)... (n)'
]

Current attempt:

import itertools

# The list of integers is like the following
# Approximate size n = 1M+
li = [0,1,2,3,4,5,6,7,8,9,10]

# Established chunked queries
def grouper(n, iterable) -> tuple:

    it: iter = iter(iterable)
    while True:
        chunk: tuple = tuple(itertools.islice(it, n))
        if not chunk:
            return
        yield chunk

queries = [f"insert into testing (testing_col) values {i};" for i in grouper(2,li)]
queries[0]

Problem is that I need to get the strings set so that that SQL engine understands single item tuples like (0), (1), etc.

Asked By: Coldchain9

||

Answers:

The tuple is a red herring from what i can gather. What you seem to want is a string that happens to have parenthesis around each term.

def process_chunk(chunk):
    return 'insert into test_table (test_col) values ' + ', '.join(f'({x})' for x in chunk) + ';'

def process_all(data, n):
    return [process_chunk(data[i:i+n]) for i in range(0, len(data), n)]
Answered By: Mikael Öhman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.