I have the below query using execute to add data using execute, what would be a executemany version of this code?
import psycopg2
import os
from dotenv import load_dotenv
load_dotenv()
urlstocopy = return_list_urls2(1300000)
def main():
# fake values
conn_string = "host='db-etherator-do-user--0.b.db.oean.com' port='60' dbname='etherr2' user='in' password='sadf'"
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
# convert them into list of tuples
x = 1
for link in urlstocopy:
values = (x, '', '', '', '', link, '2022-10-10', '2022-10-10')
sql = f'''insert into accounts_website(id, business_name, industry, trade, acc_notes,website,created_on,updated) values{str(values)}'''
cursor.execute(sql)
conn.commit()
print(x)
x = x+1
conn.close()
if __name__ == "__main__":
main()
2
Answers
Your code already has a problem, because you’re not handling quoting. If there are quote characters in your URLs, your query will explode. You need this:
Using the Fast execution helpers
From the fast execution helpers link:
Where "These functions …" are
execute_batch
andexecute_values
. If you are going to deal with datasets of any size they are the way to go.