jinjasql icon indicating copy to clipboard operation
jinjasql copied to clipboard

Docs: Example for multi row insert statement (bulk insert)

Open kishaningithub opened this issue 2 years ago • 2 comments

Would like to have an example which documents how to perform bulk insert

Desired output

INSERT INTO 
    links (url, name)
VALUES
    ('https://www.google.com','Google'),
    ('https://www.yahoo.com','Yahoo'),
    ('https://www.bing.com','Bing');

kishaningithub avatar Dec 28 '21 04:12 kishaningithub

Working Code:

from jinjasql import JinjaSql

urls = [
    ("google", "https://google.com"),
    ("yahoo", "https://yahoo.com"),
    ("fb", "https://facebook.com"),
    ("twitter", "https://twitter.com"),
]

template = '''
INSERT INTO 
    links(name, url)
VALUES
{% for url in urls %}
    ( {{url[0]}}, {{url[1]}} )
{% endfor %}
'''

j = JinjaSql(param_style="qmark")

query, bindparams = j.prepare_query(template, {"urls": urls})
print(query)
print(bindparams)

Should print this:

INSERT INTO 
    links(name, url)
VALUES

    (?, ?)

    (?, ?)

    (?, ?)

    (?, ?)

['google', 'https://google.com', 'yahoo', 'https://yahoo.com', 'fb', 'https://facebook.com', 'twitter', 'https://twitter.com']

sripathikrishnan avatar Dec 28 '21 09:12 sripathikrishnan

@sripathikrishnan Thanks a ton! :-) Can i add this to readme or wiki?

kishaningithub avatar Dec 28 '21 09:12 kishaningithub