匿名用户
1级
2008-11-27 回答
将字段的类型设置成blob或者是tinyblob,然后使用new String(resultset.getBytes(col), "utf-8")来获取列中的中文
下面给个示例:
package src;
import java.io.UnsupportedEncodingException;
import java.sql.*;
public class Link {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String psw = "root";
String host = "jdbc:mysql://127.0.0.1:3306/Test?user=" + user
+ "&password=" + psw
+ "&useUnicode=true&characterEncoding=utf8";
try {
Class.forName(driver).newInstance();
try {
Connection con = DriverManager.getConnection(host);
Statement s = con.createStatement();
String sql = "select * from TB_1";
ResultSet r = s.executeQuery(sql);
while (r.next()) {
try {
System.out.println("Country:"
+ new String(r.getBytes("country"), "utf-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String update = "Insert into TB_1 (country) values('汉')";
s.executeUpdate(update);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
关于修改MYSQL字符集:
找到my.conf一般在安装目录下(Linux:/etc/mysql)找到[client],添加一行:default-character-set=utf8
再找到[mysqld]添加以下2行init_connect='SET NAMES utf8'
default-character-set=utf8,当然你也可以设置成其他字符集,不一定非要是utf8了。
重启服务后生效。