Mysql
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Mysql

Không có hoạt động nào được phép sau khi câu lệnh đóng

Tạo một lớp Tiện ích để quản lý kết nối để quản lý nó tại một điểm duy nhất trong toàn bộ ứng dụng.

Không tải DataSource mỗi khi bạn cần một kết nối mới.

Mã mẫu:

public class ConnectionUtil {

    private DataSource dataSource;

    private static ConnectionUtil instance = new ConnectionUtil();

    private ConnectionUtil() {
        try {
            Context initContext = new InitialContext();
            dataSource = (DataSource) initContext.lookup("JNDI_LOOKUP_NAME");
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    public static ConnectionUtil getInstance() {
        return instance;
    }

    public Connection getConnection() throws SQLException {
        Connection connection = dataSource.getConnection();
        return connection;
    }

    public void close(Connection connection) throws SQLException {
        if (connection != null && !connection.isClosed()) {
            connection.close();
        }
        connection = null;
    }

}

Luôn đóng kết nối và xử lý kết nối đó trong try-catch-finally

        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = ConnectionUtil.getInstance().getConnection();

            ...
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                ConnectionUtil.getInstance().close(conn);
            }
        }


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cách kết nối cơ sở dữ liệu mySQL bằng C ++

  2. Tiện ích mở rộng mysqli bị thiếu, phpmyadmin không hoạt động

  3. Ngoại lệ truyền không hợp lệ là MySQL đã được bỏ xử lý

  4. Lỗi WAMP / MySQL không đúng ngôn ngữ

  5. Nhận kết quả nằm trong bức xạ điểm đánh dấu từ cơ sở dữ liệu