我是java的新手,我需要你有关Java与Oracle DB的连接的指导。所以我现在正在做java fx,我正在为我的程序实现MVC。所以这些是相关的3个类,
的Util / ConnectionDB.java
public class ConnectionDB {
private static final String DB_USER = "WELTESADMIN";
private static final String DB_PASS = "123pass";
private static final String DB_NAME = "WEN";
private static Connection conn = null;
public boolean openConnection(){
boolean result;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.100.195:1521:"+DB_NAME+"",DB_USER,DB_PASS);
if (conn != null){
System.out.println("CONNECTION DONE");
}
result = true;
} catch (Exception e) {
e.printStackTrace();
result = false;
}
return result;
}
}
控制器/ Main.java
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("../View/login.fxml"));
primaryStage.setTitle("Weltes Oxygen Management");
primaryStage.setScene(new Scene(root));
primaryStage.show();
testConnection();
}
public void testConnection(){
ConnectionDB connect = new ConnectionDB();
connect.openConnection();
}
public static void main(String[] args) {
launch(args);
}
}
控制器/ LoginController.java
public class LoginController {
@FXML private TextField username;
@FXML private PasswordField password;
@FXML private Button loginButton;
@FXML private Label labelStatus;
@FXML private void handleLoginButton() throws InterruptedException {
Thread.sleep(1000);
labelStatus.setText("Connected...");
ConnectionDB conn = new ConnectionDB();
}
}
所以我需要使用该conn变量来建立预准备语句。如何在整个程序会话中使用连接?
提前多多感谢
答案 0 :(得分:1)
最简单的方法是你可以制作ConnectionDB单例:
public class ConnectionDB {
private static ConnectionDB instance;
public static ConnectionDB getInstance(){
if(instance == null) {
instance = new ConnectionDB();
Class.forName("oracle.jdbc.driver.OracleDriver");
instance.conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.100.195:1521:"+DB_NAME+"",DB_USER,DB_PASS);
//...... try-catch or do your stuff
}
return instance;
}
private ConnectionDB(){};
private Connection conn;
public Connection getConnection(){
return conn;
}
}
然后,只要您需要数据库连接,只需致电:
ConnectionDB.getInstance().getConnection();