Advertisement
Guest User

Untitled

a guest
Apr 10th, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. from datetime import datetime
  2. import pymysql
  3.  
  4.  
  5. conn = pymysql.connect(
  6. host='localhost',
  7. user='root',
  8. password='88zlcks',
  9. db='test',
  10. charset='utf8'
  11. )
  12.  
  13. curs = conn.cursor(pymysql.cursors.DictCursor)
  14.  
  15. single_dict = {
  16. # 'id': 1, # auto increment
  17. 'name': 'live2skull',
  18. 'insert_date': datetime.now().isoformat()
  19. }
  20.  
  21. # insert only one row
  22. sql = 'INSERT INTO test_table({keys}) VALUES({values})'.format(
  23. keys=','.join(single_dict.keys()),
  24. values=','.join(['%('+str(i)+')s' for i in single_dict.keys()]),
  25. )
  26. curs.execute(sql, single_dict)
  27.  
  28. # insert multiple rows
  29. multiple_dict = [
  30. {
  31. # 'id': 2, # auto increment
  32. 'name': 'live2skull2',
  33. 'insert_date': datetime.now().isoformat()
  34. },
  35. {
  36. # 'id': 3, # auto increment
  37. 'name': 'live2skull3',
  38. 'insert_date': datetime.now().isoformat()
  39. },
  40. ]
  41.  
  42. sql = 'INSERT INTO test_table({keys}) VALUES({values})'.format(
  43. keys=','.join(multiple_dict[0].keys()),
  44. values=','.join(['%('+str(i)+')s' for i in multiple_dict[0].keys()]),
  45. )
  46. curs.executemany(sql, multiple_dict)
  47.  
  48. conn.commit()
  49. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement