Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 764
sabty Avatar asked Dec 27 '22 07:12

sabty


2 Answers

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).

like image 178
jjmontes Avatar answered Jan 05 '23 15:01

jjmontes


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.

like image 21
JB Nizet Avatar answered Jan 05 '23 16:01

JB Nizet