Guest User

Untitled

a guest
Mar 13th, 2019
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.91 KB | None | 0 0
  1. import pymysql
  2.  
  3.  
  4.  
  5. connection = pymysql.connect(host='localhost', user='root', password='Ro3118086', db='billing', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
  6.  
  7.  
  8. def create_update_stmt(primary='id', **rows):
  9.     fields = list(rows.keys())
  10.     fields.remove(primary)
  11.     stmt = ', '.join("{0}=VALUES({0})".format(k) for k in fields)
  12.     return stmt
  13.  
  14. def upsert_stmt(table, primary='id', **rows):
  15.     fields = rows.keys()
  16.     cols = ', '.join('{}'.format(col) for col in fields)
  17.     vals = ', '.join('%({})s'.format(col) for col in fields)
  18.     sql = 'INSERT INTO {0} ({1}) VALUES ({2}) ON DUPLICATE KEY UPDATE '.format(table, cols, vals)
  19.     sql += create_update_stmt(primary, **rows)
  20.     return sql
  21.  
  22. def upsert_db(table,primary, **kwargs):
  23.     with connection.cursor() as cur:
  24.         qry = upsert_stmt(table,primary=primary, **kwargs)
  25.         cur.execute(qry, kwargs)
  26.         connection.commit()
Add Comment
Please, Sign In to add comment