Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import sys
- import MySQLdb
- _column_types = ('varchar', 'char', 'text', 'enum', 'set')
- if __name__ == '__main__':
- if len(sys.argv) < 2:
- print 'ERROR - database name is required'
- print 'mysql-db-to-utf8.py dbname [dbuser] [dbpassword]'
- sys.exit(1)
- dbname = sys.argv[1]
- dbuser = (2 not in sys.argv) and sys.argv[2] or 'root'
- dbpass = (3 not in sys.argv) and sys.argv[3] or ''
- conn = MySQLdb.connect(host='localhost', db=dbname, user=dbuser, passwd=dbpass)
- c = conn.cursor()
- c.execute('ALTER DATABASE `' + dbname + '` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci')
- print 'Database ' + dbname + ' default character set changed to utf8'
- c.execute('SHOW TABLES')
- tables = tuple(table[0] for table in c.fetchall())
- for table in tables:
- c.execute('ALTER TABLE `' + table + '` COLLATE utf8_general_ci')
- print '* Table %s collation changed to utf8' % (table)
- c.execute('SHOW COLUMNS FROM `' + table + '`')
- cols = tuple((col[0], col[1]) for col in c.fetchall())
- for col in cols:
- for col_type in _column_types:
- if col[1].find(col_type) != -1:
- c.execute('ALTER TABLE `' + table + '` CHANGE `' + col[0] + '` `' + col[0] + '` ' + col[1] + ' CHARACTER SET utf8 COLLATE utf8_general_ci')
- print ('..' * 5) + ' column ' + col[0] + ' character set changed to utf8'
- break
Add Comment
Please, Sign In to add comment