java插入mysql数据库乱码(紧急)
来源:百度知道 编辑:UC知道 时间:2024/05/29 10:13:08
在server.xml中配置的是url="jdbc:mysql://localhost:3306/check?autoReconnect=true
如果加上&characterEncoding=gbk会报错。
另外数据库都是GBK。
在方法中:
String sql = "insert into tab_team (teamid,teamname) values('"+t.getTeamid()+"','"+t.getTeamname()+"');";
ps = c.prepareStatement(sql);
int r = ps.executeUpdate();
System.out.println("sql: ==" + sql);
打印出来:
sql: ==insert into tab_team (teamid,teamname) values('02','交行运维');
没问题,但是在数据库中看就是乱码(通过MySQL-Front)
我以前使用没问题,重装系统后,这个开发系统也重新导入,数据库也重新导入后,就出现这个问题了。
应该是数据库的编码格式的问题,你试试插入数据库的时候字符串转换一下格式看看.
String newStr=new String(name.getBytes("ISO-8859-1"),"UTF-8")
改成UTF-8试试看,不行就转成ISO-8859-1
多试试,应该可以解决的
如果修改数据库的设置可能会让开发过的其他项目有问题的
1楼说的方法是正确的。他保证你插入的中文是正确编码到数据库。在数据库中显示正常。你可以使用sql-front工具看看插入到数据库中的数据库是否正常。
如果正常了,显示乱码,就是应用的问题。可以使用过滤器解决。
大家可以试试这个:
public static Connection getConn() throws SQLException
{
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String url="jdbc:mysql://localhost:3306/gwap?useUnicode=true&characterEncoding=utf-8";
String username="root";
String password="";
conn=DriverManager.getConnection(url,username,password);
if(conn!=null)
{
System.out.println("数据库连接成功");
}
else
{
System.out.print