Excuse me for my english. I have a problem trying to connect to MySQL database from my Java code. I've created database + tables. I tried to insert some values in russian, but got a lot of question marks. After that I googled a lot and found out how to change mysql charset. I added this to my.cnf
[mysqld]
collation-server = utf8_unicode_ci
init-connect='SET NAMES utf8'
character-set-server = utf8
character-set-filesystem = utf8
After restart of the app, I could add and see Russian letters in Database using terminal (terminal->'mysql'->'USE database_name;'->'SELECT * FROM table_name;') and got setting shown here:
show variables like 'char%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
show variables like 'collation%';
+----------------------+-----------------+
| Variable_name | Value |
+----------------------+-----------------+
| collation_connection | utf8_general_ci |
| collation_database | utf8_unicode_ci |
| collation_server | utf8_unicode_ci |
+----------------------+-----------------+
But when I tried to get this data from Java – I failed again. I've already found out that I should connect like this, but it didn't help.
jdbc:mysql://localhost:3306/database_name?useUnicode=true&characterEncoding=utf8
Here is my Java code:
results = statement.executeQuery(req);
if (!results.next()) return null;
byte bytes[] = results.getBytes(1);
String value = new String(bytes, "UTF-8");
return value;
-----ALSO TRIED JUST LIKE THIS-----
results = statement.executeQuery(req);
if (!results.next()) return null;
return results.getString(1);
What should I do? Thank you.
The problem was not in the MySQL part. The problem was in printing the result, but another problem is that I tried to save Emojis to the DB, but understood that utf8 is not, as good as I thought. I found out that I should convert my DB to utf8mb4 to handle Emojis, but there is a problem, because I can't proceed this string from tutorial:
ALTER DATABASE app-data CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-data CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci' at line 1