Copy a table from one database to another


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. type_str = type('str')
  2. type_datetime = type(datetime.datetime.now())
  3. type_int = type(1)
  4. type_float = type(1.0)
  5. type_None = type(None)
  6.  
  7.  
  8. #todo: handle blob data type
  9.  
  10. def convert2str(record):
  11. res = []
  12. for item in record:
  13. if type(item)==type_None:
  14. res.append('NULL')
  15. elif type(item)==type_str:
  16. res.append('"'+item+'"')
  17. elif type(item)==type_datetime:
  18. res.append('"'+str(item)+'"')
  19. else: # for numeric values
  20. res.append(str(item))
  21. return ','.join(res)
  22.  
  23.  
  24.  
  25. def copy_table(tab_name, src_cursor, dst_cursor):
  26. sql = 'select * from %s'%tab_name
  27. src_cursor.execute(sql)
  28. res = src_cursor.fetchall()
  29. cnt = 0
  30. for record in res:
  31. val_str = convert2str(record)
  32. try:
  33. sql = 'insert into %s values(%s)'%(tab_name, val_str)
  34. dst_cursor.execute(sql)
  35. cnt += 1
  36. except:
  37. print cnt, val_str
  38. return cnt

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.