我在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;
}
}
}
答案 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()
。