使用JDBC的方法連接不上MySQL,我的網絡是校園網,登陸後IP會變化,不知道這個對連接有沒有什麼影響,用的是mysql 5.6 以前用JDBC連接上過的,但是現在就不行了,不清楚原因,也在網上找過,但是找不到解決的辦法,連接的JAR包是mysql-connector-java-5.1.26-bin.jar,請知道的大神解答一下小弟,還有就是使用Oracle用JDBC是連接得上的,使用的地址也是localhost,但是在用JDBC連接數據庫查看的時候,在使用preparedStatement返回的genernatekeys無法使用getInt這個方法,所以想用mysql,因為視頻教程中也是用MySQL的,並且是能用getInt這是方法的,所以想用mysql,麻煩各位大哥幫幫忙 出現的錯誤如下:
import java.sql.*;
public class TestMysqlConnection {
public static void main (String[] args) {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bbs","root","123456");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
錯誤如下:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Communication link failure, message from server: "Can't get hostname for your address"
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1112)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2486)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2519)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2304)
at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:834)
at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:346)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at TestMysqlConnection.main(TestMysqlConnection.java:8)
不好意思,已經找到了解決的方法了,是因為安裝MySQL的時候,它的服務-登陸為:自動選擇的是網絡服務,修改為本地系統就可以了,謝謝大家的回答!