How to insert arabic word into mysql database using java

I have a Java application, you want to insert arabic words into mysql database, my code looks like

Connection con = null;
    String url = "jdbc:mysql://localhost/";
    String db = "students";
    String driver = "com.mysql.jdbc.Driver";
    try {
        Class.forName(driver);
        con = DriverManager.getConnection(url+db,"root","");
        Statement st = con.createStatement();
        String name = new String(txtName.getText().getBytes(), "UTF-8");
        int val = st.executeUpdate("insert into student(name, roll) VALUES('"+name+"','"+txtRoll.getText()+"')");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

But he only inserts '??????'. what can i do now

+5
source share
4 answers

add this variable after the db variable declaration:

String unicode= "?useUnicode=yes&characterEncoding=UTF-8";

and then change your line:

con = DriverManager.getConnection(url+db,"root","");

to

con = DriverManager.getConnection(url+db+unicode,"root","");
+18
source

i ran into the same problem, but with Chinese data, and this is not only UTF8 in the db connection - this is a solution you should also make:

, MySQL . my.cnf " linux" my.ini ",

[client] 
default-character-set=utf8

[mysql]
default-character-set=utf8

[mysqld]
default-character-set=utf8
character-set-server=utf8
+1

UTF-8, , , ...

second you need to encode it before saving it, i like to use unicode ... one thing about this is that if you have a column that indicates the length is 32, you will have to increase this for unicode as one character takes 6 characters ,

Example

the letter h is displayed as U + 0068

0
source

@maerics I tried using PreparedStatement instead, and the SQL Injection attack can still be executed, I think that the PreparedStatemnt is not executing correctly or your channel is incorrect.

0
source

All Articles