Mysql乱码问题

来源:互联网 发布:linux 小红帽下载 编辑:程序博客网 时间:2024/05/29 10:08

今天早上各种设置Mysql的字符集以及Eclipse的字符集与String字符集的转换,最后尝试各个字符集的测试,但是在mysql数据库中还是中文出现乱码。最终在一篇论坛中找到了解决办法,由于自己在链接数据库时没有设置字符集,导致在数据库中所有的中文都是乱码。

package com.mysqltest;import java.io.UnsupportedEncodingException;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;import com.mysql.jdbc.Connection;public class MySql {  public static String driver = "com.mysql.jdbc.Driver";public static String url = "jdbc:mysql://localhost/testone?characterEncoding=UTF-8"; //此处忘记设置字符集编码,最后导致自己调试了一上午public static String user = "root";public static String password = "1234";public static Statement stmt = null;public static java.sql.Connection conn = null;    public static void datatoMySql(String insertSQl) {try {try {Class.forName(driver).newInstance();} catch (Exception e) {System.out.println("Unable to find the local driver");e.printStackTrace();}conn = DriverManager.getConnection(url, user, password);stmt = conn.createStatement();} catch (SQLException e) {e.printStackTrace();}try {stmt.executeUpdate(insertSQl);} catch (SQLException e) {e.printStackTrace();}try {stmt.close();conn.close();} catch (SQLException e) {e.printStackTrace();}}public static void main(String []args){MySql my = new MySql();String str = "你好";try {String newstr = new String(str.getBytes(),"utf8");String insertsql = "insert into test(id,name,value) value('2','"+newstr+"','content1')";my.datatoMySql(insertsql);System.out.println(newstr);} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}



0 0