2017-09-24 345 views
1

我是JDBC的新手。我剛剛嘗試將我的java程序與Mysql數據庫連接時遇到了SQLException。JDBC連接失敗:java.sql.SQLException:通信鏈接失敗:錯誤的握手

請找到運行時錯誤的下面的詳細信息:

Exception in thread "main" java.sql.SQLException: Communication link failure: Bad handshake 
    at com.mysql.jdbc.MysqlIO.init(Unknown Source) 
    at com.mysql.jdbc.Connection.connectionInit(Unknown Source) 
    at com.mysql.jdbc.jdbc2.Connection.connectionInit(Unknown Source) 
    at com.mysql.jdbc.Driver.connect(Unknown Source) 
    at java.sql.DriverManager.getConnection(DriverManager.java:664) 
    at java.sql.DriverManager.getConnection(DriverManager.java:247) 
    at databaseexample.DatabaseExample.connect(DatabaseExample.java:40) 
    at databaseexample.DatabaseExample.main(DatabaseExample.java:26) 
/home/sreejith/.cache/netbeans/8.2/executor-snippets/run.xml:53: Java returned: 1 

Program Details : 
package databaseexample; 
import java.sql.* 

;

public class DatabaseExample { 

    static boolean flag = false; 
    static String DBURL = "jdbc:mysql://localhost:3306/testdb"; 


    static String CHECK_SQL_QUERY = "SELECT 1"; 
    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) throws SQLException, ClassNotFoundException { 
     // TODO code application logic here 
     Class.forName("com.mysql.jdbc.Driver"); 
     flag = connect(); 
     if(flag == true) 
     { 
      System.out.println("Connnected !"); 
     } else 
     { 
      System.out.println("not connected."); 
     } 



    } 

    public static boolean connect() throws SQLException { 
     Connection conn = DriverManager.getConnection(DBURL,"root","root"); 

     return true; 
    } 

} 

我試圖telnet端口3306,如下收到了結果:

[email protected]:~$ telnet localhost 3306 
Trying 127.0.0.1... 
Connected to localhost. 
Escape character is '^]'. 
[ 
5.7.19-0ubuntu0.16.04.1*4` `iw2)Ml,L* 
             Lmysql_native_password 

!#08S01Got packets out of orderConnection closed by foreign host. 

我在Ubuntu 16.04的方式運行。 感謝提前:)

+0

檢查可能重複:https://stackoverflow.com/questions/6865538/solving-a-communications-link-failure-with-jdbc- and-mysql – 2017-09-24 03:53:39

回答

-1

試試這個方法:

import java.sql.DriverManager; 
import java.sql.SQLException; 

public class Connection 
{ 
    private static java.sql.Connection connection; 

    public Connection(String serverAddress, String database, String user, String pass) throws ClassNotFoundException, SQLException 
    { 
     Class.forName("com.mysql.jdbc.Driver"); 
     String url = "jdbc:mysql://" + serverAddress + ":3306/" + database; 
     connection = DriverManager.getConnection(url, user, pass); 
    } 

    public java.sql.Connection getConnection() 
    { 
     return connection; 
    } 
} 
+0

這是一個建議,而不是OP發佈的問題的答案,不符合答案! –

+0

這與OP使用的代碼有何不同?提示:實質上它是一樣的。 –

+0

嗨Ramin ..我試着用你的代碼,仍然面臨着同樣的錯誤:(..有人可以通過某種方式來解決這個問題嗎?它是數據庫連接字符串的問題嗎? –