2016-05-31 71 views
-2

我已經在Java中創建了兩個應用程序,並且我想將它們連接到同一個數據庫中。任何人都可以幫助我的代碼示例?Java應用程序連接在同一個數據庫中

import java.sql.*; 
    import javax.swing.*; 

    public class LidhjaMeSQL { 
     Connection connection=null; 

    public static Connection ConnectDB(){ 
     //struktura e kontrollit try-catch 
     try{ 
      Class.forName("com.mysql.jdbc.Driver"); 
      Connection connection=DriverManager.getConnection("jdbc:mysql://localhost/database","root",""); 
      return connection; 
     }catch(ClassNotFoundException | SQLException e){ 
      JOptionPane.showMessageDialog(null, e); 
      return null; 
     } 
    } 
} 
+2

你有兩個程序要同時連接到同一個數據庫嗎?有什麼問題? –

+0

是的,我想連接兩個應用程序在同一個數據庫,但Class.forName(「com.mysql.jdbc.Driver」);給我錯誤。 –

+0

你會得到什麼錯誤?我需要細節。我們無法猜出發生了什麼 –

回答

0

試試這個:

public class LidhjaMeSQL { 
    public Connection connectDB() { 
     try { 
      Class.forName("com.mysql.jdbc.Driver"); 
      Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/database", "root", ""); 
      return connection; 
     } catch (ClassNotFoundException | SQLException e) { 
      //handle exception here.. 
     } 
    } 
} 

現在去到你想打開的連接class。簡單地創建一個新的instanceLidhjaMeSQL並致電connectDB()

相關問題