Search code examples
pythoncx-oracleexecutemany

Writing Generic cursor.executemany() in python


Im new to python, trying to write a generic function that has arguments as the list of dictionaries, tablename, dbusername, password and Insert different data in to different tables like below

dict_list=[{'name': 'sandeep', 'age': '10'}, {'name': 'sa', 'age': '0'}] another_dict_list=[{'area': 'AP', 'pin': '00'}, {'area': 'UP', 'pin': '01'}]

def func(listofdict, tablename, dbusername, dbpassword):
  #all connection and cursor code  here#
  query = """insert into tablename (dict keys) values(dict values)"""
  cursor.executemany(query, listofdict)

now ill call the above funtion

func(dict_list, nametable, dbuser, dbpassword)
func(another_dict_list ,areatable, dbuser, dbpassword)

Wanted to know if we can write a generic code for insertion of data using execute many


Solution

  • Assuming that the list of dictionaries contain at least one entry and each entry has the same keys, you can do the following:

    def func(table_name, args):
        names = list(args[0].keys())
        column_names = ",".join(names)
        bv_names = ",".join(":" + n for n in names)
        sql = f"insert into {table_name} ({column_names}) values ({bv_names})"
        cursor.executemany(sql, args)
    

    The first line assumes that there is at least one entry in args and that it is a dictionary and that all subsequent entries are also dictionaries with the same keys. If any of those assumptions are incorrect the function will fail.

    The next few lines build up the SQL that you want to execute with the bind variables.