有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java MYSQL一个类一个连接

我正在学习MySQL数据库,我不能完全理解一个概念。假设同一个类中有两个方法,如下所示。现在,我必须使用Connection connect=dbConnection吗。getDBConnection();在每个方法中,是否有不同的方法来声明一个连接并跨多个方法使用它

private void setUpdateButton(ActionEvent event) {
    try{
        Connection connect = dbConnection.getDBConnection();
        Statement stmt = connect.createStatement();


        if(txtID.getText().trim().isEmpty()||txtFirstName.getText().trim().isEmpty() || txtSecondName.getText().trim().isEmpty() ||
                txtGender.getText().trim().isEmpty() || txtAge.getText().trim().isEmpty() || txtHomeAddress.getText().trim().isEmpty() || txtPhoneNumber.getText().trim().isEmpty()) {
            showAlert("Invalid Input!", "All fields need to be populated before updating.");
        }else {
               String sqlQuery ="update student_information set Age ='"+Integer.parseInt(txtAge.getText())+"',Name ='"+txtFirstName.getText()+"',Surename='"+txtSecondName.getText()
            +"',Gender='"+txtGender.getText()+"',Address='"+txtHomeAddress.getText()+"',PhoneNumber='"+txtPhoneNumber.getText()+"'where ID="+Integer.parseInt(txtID.getText());
               stmt.executeLargeUpdate(sqlQuery);
               setTxtArea();
               showConfAlert("Update Completed!", "Record has been updated!");

共 (1) 个答案

  1. # 1 楼答案

    创建连接是一项代价高昂的操作,因此我认为应该在应用程序启动时打开连接,并在退出时关闭

    如果你的程序不是多线程的,你可以使用一个简单的全局对象,否则应该使用其他策略

    你可以使用返回连接的方法为你的应用创建一个单例

    public class App {
        private static App self;
    
        private Connection connection;
    
        private App(){
        }
    
        public synchronized App getInstance(){
            if(self == null){
                self = new App();
            }
            return self;
        }
    
    
        public synchronized Connection getConnection()throws SQLException {
            if(connection==null || !isValid(connection)){
                // Create a new connection 
            }
            return connection;
        }
    
        private boolean isValid(Connection conn) {
            // Check if the connection is valid otherwise return false 
            return false;
        }
    
    
        public static synchronized void close(){
            try{
                self.connection.close();
            } catch (SQLException e){
                // Swallow exception
            } finally {
                self = null;
            }
        }
    
    }
    

    你可以在任何地方获得这样的连接:

    Connection conn = App.getInstance().getConnection();
    

    你应该确保在出口处关闭连接,可能是用关机挂钩

    您还可以在连接周围创建一个包装器,将所有连接方法转发到原始连接,除了标记连接可用的close之外,这样可以创建类似于1个连接池的东西

    如果连接可用,则返回连接,否则,您可以等待或抛出连接,或者执行最适合您的应用程序的操作