Guest User

Untitled

a guest
May 8th, 2018
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import sys
  5. import MySQLdb
  6.  
  7. _column_types = ('varchar', 'char', 'text', 'enum', 'set')
  8.  
  9. if __name__ == '__main__':
  10. if len(sys.argv) < 2:
  11. print 'ERROR - database name is required'
  12. print 'mysql-db-to-utf8.py dbname [dbuser] [dbpassword]'
  13. sys.exit(1)
  14.  
  15. dbname = sys.argv[1]
  16. dbuser = (2 not in sys.argv) and sys.argv[2] or 'root'
  17. dbpass = (3 not in sys.argv) and sys.argv[3] or ''
  18.  
  19. conn = MySQLdb.connect(host='localhost', db=dbname, user=dbuser, passwd=dbpass)
  20. c = conn.cursor()
  21.  
  22. c.execute('ALTER DATABASE `' + dbname + '` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci')
  23. print 'Database ' + dbname + ' default character set changed to utf8'
  24.  
  25. c.execute('SHOW TABLES')
  26. tables = tuple(table[0] for table in c.fetchall())
  27.  
  28. for table in tables:
  29. c.execute('ALTER TABLE `' + table + '` COLLATE utf8_general_ci')
  30. print '* Table %s collation changed to utf8' % (table)
  31.  
  32. c.execute('SHOW COLUMNS FROM `' + table + '`')
  33. cols = tuple((col[0], col[1]) for col in c.fetchall())
  34.  
  35. for col in cols:
  36. for col_type in _column_types:
  37. if col[1].find(col_type) != -1:
  38. c.execute('ALTER TABLE `' + table + '` CHANGE `' + col[0] + '` `' + col[0] + '` ' + col[1] + ' CHARACTER SET utf8 COLLATE utf8_general_ci')
  39. print ('..' * 5) + ' column ' + col[0] + ' character set changed to utf8'
  40. break
Add Comment
Please, Sign In to add comment