乱码问题解决
在web表单里每次输入中文的firstName和lastName的时候,显示出来都是乱码,几乎可以认定是编码不统一的问题,可是一直都没找到问题的源头,查阅资料显示java内存默认的编码是iso8859-1 (也叫latin-1)不支持中文 , 而我在jsp界面设置的都是utf-8,可是看我myeclipse的设置里默认的都是gbk,貌似问题不在这儿,于是就不停的设置断点
每次都是到pStatement.setString(1, employee.getFirstName());时,明明emploee.getFirstName()取出来的是中文,一到PreparedStatement里就成了?号,那问题到底在哪儿呢,一个connction终于让我觉得问题貌似就在数据库方面,mysqlFront似乎都是正常的,抱着尝试的态度我使用了mysql的命令行,结果select发现中文字体在命令行都是??,难道是mysql默认编码的问题
于是进入mysql自带的config-MySQL Server Instance Config Wizard,意外发现默认编码是latin1,突然心情小激动了下,果断改成utf-8,一切就绪,如我所料,搞定中文乱码,都是mysql默认编码不支持中文惹的祸,内牛满面
附上关键代码:
private static final String CREATE_EMPLOYEE_SQL = "INSERT INTO employees (firstName,lastName) VALUES (?, ?)";
public void createEmployee(Employee employee) throws DAOException {
Connection connection = null;
PreparedStatement pStatement = null;
try {
connection = getConnection();
// mysql的默认编码设置为utf-8,否则不能传入中文字符
pStatement = connection.prepareStatement(CREATE_EMPLOYEE_SQL);
pStatement.setString(1, employee.getFirstName());
pStatement.setString(2, employee.getLastName());
System.out.println("运行到employee.getFirstName() :"+ employee.getFirstName());
pStatement.executeUpdate();
pStatement.close();
} catch (SQLException ex) {
throw new DAOException();
} finally {
try {
connection.close();
} catch (SQLException ex) {
throw new DAOException();
}
}
}
结果图: