早教吧 育儿知识 作业答案 考试题库 百科 知识分享

java连接mysql时Communicationslinkfailurepublicstaticvoidmain(String[]args){Connectionconn=null;Statementstmt=null;ResultSetrs=null;try{Class.forName("com.mysql.jdbc.Driver");conn=DriverManager.getConnection("jdbc:mysql

题目详情
java 连接 mysql时Communications link failure
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");

conn = DriverManager
.getConnection("jdbc:mysql://localhost/mydata?user=root&password=root");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from dept");
while (rs.next()) {
System.out.println(rs.getString("deptno"));
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}

}

}
▼优质解答
答案和解析
把localhost换成127.0.0.1看看,看看防火墙的3306端口打开没有,检查mysql看看用的是不是不是3306.