Inserting Arabic characters into mySQL DB using java (SE)
I have three textfields (ID,Name,Address) which reflects columns in DB table i'm trying to insert arabic characters into that table but it appears as "?????"
iam connecting to DB using JDBC
my Database info. : MySQL Server 5.5.14 community Server characterset: latin1 Db characterset: utf8 Client characterset: latin1 开发者_如何学JAVAConn. characterset: latin1i try to encode strings using the following code:
private String ArEncode(String text){
String txt="";
try {
Charset cset = Charset.forName("utf8");
CharsetEncoder encoder = cset.newEncoder();
CharsetDecoder decoder = cset.newDecoder();
ByteBuffer buffer = encoder.encode(CharBuffer.wrap(text));
txt=buffer.asCharBuffer().toString();
} catch (Exception ex) {
Logger.getLogger(UserView.class.getName()).log(Level.SEVERE, null, ex);
}
return txt;
}
then the returned string "txt" is inserted in to the database
note: when i try to insert values directly into DB from netbeans it is inserted correctly and the Arabic characters appears correctly.
Why would you do this? It's the job of the mysql JDBC driver to encode strings correctly in the declared database character set. Set your character set in the database to UTF-8, set the JDBC options correctly, and just do a plain insert of a plain old String.
your encoding logic should if it works correctly return the exact same value in txt
as in text
thus it is not needed.
And: set the connection characterset to utf8 - the JDBC will/should take care of the rest...
精彩评论