运行xampp-win32- 1.5.5 -installer.exe,安装了xampp后,其自带的mysql是5.0.27版的,安装一切正常,成功后访问数据库也没问题,在数据库操作一切也正常。
但我写了个简单的java程序访问数据库时,却出现了问题。原程序如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DAOTest {
private static final String URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";
private static final String USERNAME = "root";
private static final String PASSWORD = "root";
private static final String DRIVER = "com.mysql.jdbc.Driver";
public static Connection getConnection() {
try {
Class.forName(DRIVER);
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException ce) {
throw new java.lang.RuntimeException(ce);
} catch (SQLException se) {
throw new java.lang.RuntimeException(se);
}
}
public static void main(String[] args){
Connection conn=getConnection();
try{
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select * from user");
while(rs.next())
System.out.println(rs.getString("username"));
}catch(SQLException e){
e.printStackTrace();
}
}
}
运行后问题如下:
Exception in thread "main" java.lang.RuntimeException: java.sql.SQLException: Unknown initial character set index '48' received from server. Initial client character set can be forced via the 'characterEncoding' property.
at com.kemei.database.dao.DAOTest.getConnection(DAOTest.java:25)
at com.kemei.database.dao.DAOTest.main(DAOTest.java:29)
Caused by: java.sql.SQLException: Unknown initial character set index '48' received from server. Initial client character set can be forced via the 'characterEncoding' property.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
at com.mysql.jdbc.Connection.configureClientCharacterSet(Connection.java:2345)
at com.mysql.jdbc.Connection.initializePropsFromServer(Connection.java:3913)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2683)
at com.mysql.jdbc.Connection.<init>(Connection.java:1531)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(DriverManager.java:525)
at java.sql.DriverManager.getConnection(DriverManager.java:171)
at com.kemei.database.dao.DAOTest.getConnection(DAOTest.java:21)
... 1 more
从错误的提示信息中发现字符集设置出现问题,于是想到可能是xampp自带mysql的配置文件可能出有问题。于是到mysql/bin目录下,找到my.cnf,打开该文件,把
collation-server = latin1_general_ci改为collation-server = latin1_swedish_ci,重启数据库,再运行该程序,问题解决。