Posted By

bingjian on 08/18/09


Tagged

database sql


Versions (?)

Copy a table from one database to another


 / Published in: Python
 

  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
Posted By: angelopellef1 on December 25, 2013

it gives me an error on datetime:

type_datetime = type(datetime.now()) NameError: name 'datetime' is not defined

You need to login to post a comment.