Java ResultSet Closed how to fix it

The problem is when I click on the Update Button to Insert Form to textfield where I can edit Appointments but when I click the UpdateButton there was An error "Result Set Closed"

The problem is when I click on the Update Button to Insert Form to textfield where I can edit Appointments but when I click the UpdateButton there was An error "Result Set Closed"

try {
    int row = jTable5.getSelectedRow();
    String Table_Click = (jTable5.getModel().getValueAt(row,0).toString());
    String sql = "Select Ap.Appointment_ID,Ap.Doc_ID,(Ut.First_Name) As Doc_FirstName,Ut.Middle_Name As Doc_MiddleName,Ut.Last_Name As Doc_LastName,Ap.Department_ID,Dt.Department_Name,Ap.Patient_ID,Pr.First_Name,Pr.Middle_Name,Pr.Last_Name,Ap.SchedDate,Ap.Description,Ap.App_Date_Registered from Appointment_Table As Ap\n" +
                     "inner join User_Table As Ut on Ap.Doc_ID=Ut.ID\n" +
                     "inner join Patient_Records As Pr on Ap.Patient_ID=Pr.Patient_ID\n" +
                     "inner join Department_Table As Dt on Ap.Department_ID=Dt.Department_ID\n" +
                     "where Appointment_ID = '"+Table_Click+"'";
    pst = conn.prepareStatement(sql);
    rs = pst.executeQuery();
if (rs.next()) {
    String add0 = rs.getString("Appointment_ID");
    AppointmentID.setText(add0);
    String add1 = rs.getString("Department_Name");
    DoctorDep_Update.setSelectedItem(add1);
    String add2 = rs.getString("Doc_FirstName");
    DoctorName_Update3.setText(add2);
    ....
}

} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
} finally {
try {
rs.close();
pst.close();
} catch(Exception e) {

}

}

When I put

String add2 = rs.getString("Doc_FirstName");
DoctorName_Update3.setText(add2);

the error appears I think there is some mistake in my query but I cannot solve it.. when I try to run it on SQlite Browser result show up

Exception

java.sql.SQLException: ResultSet closed
at org.sqlite.RS.checkOpen(RS.java:57)
at org.sqlite.RS.findColumn(RS.java:103)
at org.sqlite.RS.getString(RS.java:247)
at Portal.ReceptionistPortal.Update_AppointmentsActionPerformed(ReceptionistPortal.java:7912)
at Portal.ReceptionistPortal.access$1900(ReceptionistPortal.java:32)
at Portal.ReceptionistPortal$24.actionPerformed(ReceptionistPortal.java:2256)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6539)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6304)
at java.awt.Container.processEvent(Container.java:2239)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2297)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
at java.awt.Container.dispatchEventImpl(Container.java:2283)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
at java.awt.EventQueue$4.run(EventQueue.java:733)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

it is saying that the error is on

String add2 = rs.getString("Doc_FirstName");
DoctorName_Update3.setText(add2);


Database Caching With Redis and Java

Database Caching With Redis and Java

Explore database caching with Redis and Java and see some of the different caching strategies.

Explore database caching with Redis and Java and see some of the different caching strategies.

Why Is Database Caching so Important?

The more information you have in a database, the slower it will become over time. Even database management systems that are well-designed to support many concurrent requests will eventually hit their limit.

Database caching is one of the most common strategies for dealing with these performance issues. Caching involves saving the results of database queries in a location that is faster and easier to access. When done correctly, caching will slash query response times, decrease the load on your databases, and cut costs.

However, caches also need to be handled with care because they essentially make another copy of your information in a separate location. Keeping both the database and the cache synchronized and up-to-date can be a trickier challenge than you anticipated. In the next section, we’ll discuss some of the most common database caching strategies.

What Are the Different Caching Strategies?

Manual caching (also known as a cache-aside strategy) involves direct management of both the database and the cache. Your application inspects the cache before launching a database query, and it updates the cache after any changes to the database.

While effective if implemented correctly, manual caching can be extremely tedious, especially if you need to query more than one database. For these reasons, developers have invented a number of alternative caching strategies.

Read-Through Caching Strategy

In read-through caching, the application first queries the cache to see if the information it needs is inside. If not, it retrieves the information from the database and uses it to update the cache. The cache provider or cache library is responsible for the detailed logic of querying and updating the cache.

The read-through strategy works best for read-heavy workloads when the application requests the same data repeatedly: for example, a news website that loads the same articles over and over.

One downside of the read-through strategy is that the first query to the cache will always result in a miss because the requested information is guaranteed not to be inside. To deal with this issue, developers often “warm” the cache ahead of time with information that users are likely to request.

Write-Through Caching Strategy

In write-through caching, updates are made to the cache first and to the database second. There is a direct line from the application to the cache and from the cache to the database. When combined with read-through caching, a write-through strategy guarantees that your data will be consistent, removing the need for manual cache invalidation.

Write-Behind Caching Strategy

In write-behind caching (also known as write-back caching), the application first writes data to the cache. After a set period of delay, the cache writes this information to the database as well. Write-behind caches are best for write-heavy workloads and can perform well even with some failures and downtime.

Java-Based Redis Caching With Redisson

Redis is one of the most popular options for NoSQL databases, using a key-value system to store data. Redisson, a client library for Redis in the Java programming language, makes it easy to access Redis features using all the familiar Java collections.

Redisson allows you to place data in Maps in external storage. You can use this functionality to implement caching for databases, web services, or any other data source.

Read-Through Caching in Redis

Below is a Java example of how to use read-through caching in Redis with Redisson.

If the requested entry doesn’t exist in the cache, it will be loaded by MapLoader object:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

Configuration example:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

Write-Through Caching in Redis

Below is a Java example of how to use write-through caching in Redis in Redis with Redisson.

Cache update method will not return until both the cache and the database have been updated by MapWriter object:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

Configuration example:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

Write-Behind Caching in Redis

The MapWriter interface is also used to asynchronously commit updates to the Map object (cache) and the external storage (database). Threads amounts used in the background write operation execution sets through the writeBehindThreads setting.

Below, we see a Java example of the configuration for a Redis-based write-behind caching implementation in Redisson:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

All discussed strategies are available for the RMap, RMapCache, RLocalCachedMap, and RLocalCachedMapCache objects in Redisson. Using these latter two objects can make read operations in Redis up to 45 times faster.

Insert File Into MySQL Database In Java

Sometimes we have a requirement to insert file into database rather then storing it in the file system. For a developer, it is always hard to decide this. You can find good discussion in different forums on web over storing the file either in database or file system. I believe choosing the same depends on the project requirement rather than preferences. You can choose database over file system when file size is small and user’s file needs to be more tightly coupled, secured and confidential. Since this discussion is out of scope of this article, here is a good resource,&nbsp;<a href="https://habiletechnologies.com/blog/better-saving-files-database-file-system/" target="_blank">Which is Better ? Saving Files in Database or File System</a>&nbsp;for your reference.

Introduction

Sometimes we have a requirement to insert file into database rather then storing it in the file system. For a developer, it is always hard to decide this. You can find good discussion in different forums on web over storing the file either in database or file system. I believe choosing the same depends on the project requirement rather than preferences. You can choose database over file system when file size is small and user’s file needs to be more tightly coupled, secured and confidential. Since this discussion is out of scope of this article, here is a good resource, Which is Better ? Saving Files in Database or File System for your reference.

Well, today we will see how to insert image file into MySQL database using JDBC. We will use BLOB datatype of MySQL for storing files....

( Read More )

Java Jee ORM and Database handling

Hi,

I want to know more about Java Jee and the way it handle the database connection and his ORM