I have a MySql 5.7.20 database table called deliveries
with a column called message
which is of type blob.
I want this to be able to support special characters like emojis. I can insert and view a row with an emoji:
I know want to read this out with java. My code is:
public class JavaMysqlSelectExample
{
public static void main(String[] args)
{
try
{
// create our mysql database connection
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost/products?useUnicode=true&characterEncoding=UTF-8";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "mark", "hht6yyt6yyt6");
// our SQL SELECT query.
// if you only need a few columns, specify them by name instead of using "*"
String query = "SELECT SUBSTRING(message,1,2500) as message FROM deliveries where id = 9";
// create the java statement
Statement st = conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next())
{
String message = rs.getString("message");
// print the results
System.out.format("%s", message);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
My POM file is:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>datbase</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.jdbi/jdbi -->
<dependency>
<groupId>org.jdbi</groupId>
<artifactId>jdbi</artifactId>
<version>2.78</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
</dependencies>
</project>
But when I run it I see:
The emoji is somehow been corrupted by JDBC. What can I try?
EDIT
I've managed to read out the emoji by implementing the method:
private String convertToUTF8(String str) {
if (str == null) {
return "";
}
try {
byte[] ptext = str.getBytes("ISO-8859-1");
return new String(ptext, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error("problem converting delivery.message to UTF-8: " + e.toString());
}
return "";
}
Now I can see the emoji in the console. There's another issue now: this works with my local mysql DB but not with the one on AWS. I ran some queries:
show variables like 'collation%';
On local db it returned:
On the instance on AWS it returned:
So the difference is collation_server
. And I can't figure out how to change this. I tried running:
ALTER DATABASE products CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
But the collation_server
value is still utf8mb4_unicode_ci
.....