Get the last record from a table in MySQL database with Java?

MySQLMySQLi DatabaseJava 8

To get data from MySQL database, you need to use executeQuery() method from java. First create a table in the MySQL database. Here, we will create the following table in the ‘sample’ database

mysql> create table javaGetDataDemo
- > (
- > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
- > FirstName varchar(10),
- > LastName varchar(10)
- > );
Query OK, 0 rows affected (0.80 sec)

Now you can insert some records in the table using insert command.

The query is as follows

mysql> insert into javaGetDataDemo(FirstName,LastName) values('John','Smith');
Query OK, 1 row affected (0.19 sec)
mysql> insert into javaGetDataDemo(FirstName,LastName) values('Carol','Taylor');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from javaGetDataDemo;

The following is the output

+----+-----------+----------+
| Id | FirstName | LastName |
+----+-----------+----------+
|  1 | John      | Smith    |
|  2 | Carol     | Taylor   |
+----+-----------+----------+
2 rows in set (0.00 sec)

Now here is the Java code to get the last record from the table with the help of ORDER BY DESC clause

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class GetDataFromMySQLToJava {
   public static void main(String[] args) {
      String JdbcURL = "jdbc:mysql://localhost:3306/sample?useSSL=false";
      String Username = "root";
      String password = "123456";
      Connection con = null;
      Statement stmt = null;
      ResultSet rs = null;
      try {
         System.out.println("Connecting to database..............." + JdbcURL);
         con = DriverManager.getConnection(JdbcURL, Username, password);
         Statement st = con.createStatement();
         String query = ("SELECT * FROM javaGetDataDemo ORDER BY Id DESC LIMIT 1;");
         rs = st.executeQuery(query);
         if (rs.next()) {
            String fname = rs.getString("FirstName");
            String lname = rs.getString("LastName");
            System.out.println("FirstName:" + fname);
            System.out.println("LastName:" + lname);
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

The screenshot of Java code is as follows

The following is the screenshot of the output displaying the last record from the table

raja
Published on 19-Mar-2019 16:53:09
Advertisements