If someone is searching for a complete solution for changing default charset for all database tables and converting the data, this could be one:
DELIMITER $$
CREATE PROCEDURE `exec_query`(IN sql_text VARCHAR(255))
BEGIN
SET @tquery = `sql_text`;
PREPARE `stmt` FROM @tquery;
EXECUTE `stmt`;
DEALLOCATE PREPARE `stmt`;
END$$
CREATE PROCEDURE `change_character_set`(IN `charset` VARCHAR(64), IN `collation` VARCHAR(64))
BEGIN
DECLARE `done` BOOLEAN DEFAULT FALSE;
DECLARE `tab_name` VARCHAR(64);
DECLARE `charset_cursor` CURSOR FOR
SELECT `table_name` FROM `information_schema`.`tables`
WHERE `table_schema` = DATABASE() AND `table_type` = 'BASE TABLE';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET `done` = TRUE;
SET foreign_key_checks = 0;
OPEN `charset_cursor`;
`change_loop`: LOOP
FETCH `charset_cursor` INTO `tab_name`;
IF `done` THEN
LEAVE `change_loop`;
END IF;
CALL `exec_query`(CONCAT(
'ALTER TABLE `',
tab_name,
'` CONVERT TO CHARACTER SET ',
QUOTE(charset),
' COLLATE ',
QUOTE(collation),
';'
));
CALL `exec_query`(CONCAT('REPAIR TABLE `', tab_name, '`;'));
CALL `exec_query`(CONCAT('OPTIMIZE TABLE `', tab_name, '`;'));
END LOOP `change_loop`;
CLOSE `charset_cursor`;
SET foreign_key_checks = 1;
END$$
DELIMITER ;
You can place this code inside the file e.g. chg_char_set.sql
and execute it e.g. by calling it from MySQL terminal:
SOURCE ~/path-to-the-file/chg_char_set.sql
Then call defined procedure with desired input parameters e.g.
CALL change_character_set('utf8mb4', 'utf8mb4_bin');
Once you've tested the results, you can drop those stored procedures:
DROP PROCEDURE `change_character_set`;
DROP PROCEDURE `exec_query`;