2013-04-26 42 views
0

如何連接與我的數據庫交互的java?我正在使用XAMPP for mysql 而且我知道我使用的端口有問題..我只是複製了其他端口正在使用的互聯網但我真的不知道我的數據庫端口號是什麼 我要檢查數據庫的端口嗎? //localhost:3306如何使用java連接到數據庫

這裏是我的代碼:

try{ 
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
    System.out.print("COnnection succesfull"); 
    } 
    catch(Exception ex) 
    { 
     System.out.print("Unable to connect  "); 
    } 


    try 
    { 
     Class.forName("com.mysql.jdbc.Driver"); 
     String url = "jdbc:mysql://localhost:3306/test?user=root&password="; 
     Connection con = DriverManager.getConnection(url); 
     System.out.print("Connection Stablished"); 

    } 
    catch(Exception ex) 
    { 
     System.out.print("Connect cannot stablished"); 
    } 

回答

0

要檢查MySQL正在運行在哪個端口上,你可以檢查文件 '的my.ini' 位於 C:\ Program Files文件(x86)的\ MySQL的\ MySQL Server 5.1(Windows 8,可能會有所不同,但其安裝目錄)。

據我所知,默認值是3306。

代碼看起來正確的,但我通常

DriverManager.getConnection(url, username, password); 
0

通過用戶名和密碼,我想如果你想連接到XAMPP的MySQL中,你不需要指定端口。試試這個,這適用於我:

String dbn = "yourdatabasename"; 
     String usr = "root"; 
     String pwd = ""; 

     String connectionURL = "jdbc:mysql://localhost/"+dbn; 


     try { 

       // Load the Driver class. 
       Class.forName("com.mysql.jdbc.Driver"); 
       // If you are using any other database then load the right driver here. 


       con = (Connection) DriverManager.getConnection (connectionURL, usr, pwd); 


     } 
     catch (SQLException e) { 
      e.printStackTrace(); 
     } 
     catch (Exception e) { 
      e.printStackTrace(); 
    } 
+0

我還是不能連接 – 2013-04-26 01:54:40

+0

這個例外說了些什麼? – cakil 2013-04-26 01:59:11

+0

stablishedjava.lang.ClassNotFoundException:com.mysql.jdbc.Driver – 2013-04-26 02:07:04