How to compare utf8 text in mysql query using java

I have a problem while selecting from a table containg data in utf-8 format in MySQL using java, in the WHERE clause I need to compare if a column value equals to a java String but they don't match

"Select age from student where name = '"+stringVariable+"';"

the stringVariable can sometimes be in arabic so in this case they don't match

The database is utf8mb4 and the connection also between java and database is utf_8 and I dont have a problem while inserting or just selecting data but the problem occurs while comparing

I tried to convert the string like this and it also didnt match

byte[] b = stringVariable.getBytes("UTF-8");
String str = new String(b,"UTF-8");

So anyone has any solution for that ?!

Thank you in advance

Answer:1

Use parameters. The driver should then encode them correctly according to the connection properties.

PreparedStatement statement = connection.prepareStatement(
    "select age from student where name = ?");      
statement.setString(1, stringVariable);

In addition, this also correctly escapes special SQL characters (like single quotes).

Answer:2

You shouldn't have to transform anything. The driver takes care of everything. Try using a prepared statement rather than string concatenation. This will have the additional advantage of avoiding SQL injection attacks, and make sure your statement works even if the string variable contains a quote.

Answer:3

how to parse this date ? Mon Jul 29 02:00:00 CEST 2013 the code: public class HelloWorld{ public static void main(String []args){ try { String startdateString = ...

Is this a good idea, to group constants in classes inside Constants class container like public final class Constants { public final class File { public static final int MIN_ROWS = 1; ...

I have a bunch of model objects. These objects end up being rendered as views (say forms) in a rich client app. I started to annotate the fields in the model objects (Java annotations) with things ...

I get a lot of IndexOutOfBoundsException from the any Arraylist I use. Most of the times it works fine but sometimes I get this annoying error on Arraylists i use on my project. The main cause is ...