Python : Sqlite Insert Libraries of varying size into table


My answer accepted in stackoverflow.

Below is the code that I have written to create an insert statement for python which accepts the table name and dictionary. This will allow the varying size dictionaries to directly map into an Insert statement. Similar logical can be used for UPDATE statement as well.


import sqlite3
def create_insert_string(table_name,input_dictionary,conn_db):
#validate connection
c = conn_db.cursor()
#Check if the table is existing in the database if not throw error
table_exist=c.execute('SELECT COUNT(*) FROM sqlite_master WHERE type=\'table\' AND name=\''+table_name+'\'');
if table_exist.fetchone()[0]==0:
return 'Error'
insert_str = 'INSERT INTO '+table_name+' ( '
count=0;
for keys in input_dictionary.keys():
if count == 0:
insert_str=insert_str+ ' '+keys
else:
insert_str=insert_str+ ', '+keys
count=count+1
count=0;
insert_str=insert_str+' ) VALUES ( '
for keys in input_dictionary.keys():
if count == 0:
insert_str=insert_str+ ' :'+keys
else:
insert_str=insert_str+ ', :'+keys
count=count+1
insert_str=insert_str+' )'
return insert_str
# Main Program
conn = sqlite3.connect('C:\\PYTHON_SCRIPTS\\test.db')
dict={'column1':'value1','column2':'value2'}
insert_string=create_insert_string('test',dict,conn)
print(insert_string)
c = conn.cursor()
c.execute(insert_string,dict)
conn.commit()
c.close()