Java应用程序连接在同一个数据库中

时间:2016-05-31 19:14:29

标签: java mysql netbeans

我在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;
        }
    }
}

1 个答案:

答案 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。只需创建一个新instance LidhjaMeSQL并致电connectDB()