How can I insert arabic word to mysql database using java

I have a java application, want to insert arabic words to 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 it only insert '??????'. what can i do now?

Answers


add this variable after db variable declaration:

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

and then modify your line:

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

to

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

i faced the same problem but with Chinese data, and it is not only the UTF8 in the db connection is the solution you should also do this:

Ensure that your MySQL configuration encoding is defined correctly. Add these lines to either my.cnf "in the case if using linux" or my.ini "case you using windows"

[client] 
default-character-set=utf8

[mysql]
default-character-set=utf8

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

You have to create your database as a UTF-8 table otherwise no matter what you add it will never be able to store it...

second you need to encode it before you save it, I like to use unicode... one thing about this is that if you have a column that specifies 32 length, you will have to increase that for unicode as a single character takes up 6 characters,

example

letter h appears as U+0068


@maerics I tried using PreparedStatement instead and SQL Injection attack is still able to be done, I think either am implementing the PreparedStatemnt wrong or your feed is incorrect.


Need Your Help

GCD and async NSURLConnection

objective-c ios grand-central-dispatch

I know that if I create an NSURLConnection (standard async one), it will call back on the same thread. Currently this is on my main thread. (work fine too).

MySQL 1292 Incorrect datetime value

mysql sql-timestamp mysql-error-1292

I am getting this error when I try to insert '2011/03/13 02:53:50.000000000' into a timestamp column. If I change the 13 to a 15, 14, 12 or 11 it works no problem. I've also tried changing the /'...