How to fetch only a single result from a table in Java-MySQL?


Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (1.37 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(101,'Chris');
Query OK, 1 row affected (0.54 sec)
mysql> insert into DemoTable values(102,'David');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(103,'Mike');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+------+-------+
| Id   | Name  |
+------+-------+
| 101  | Chris |
| 102  | David |
| 103  | Mike  |
+------+-------+
3 rows in set (0.00 sec)

Let us now see the Java-MySQL code. This will fetch only a single record from the top of the table −

Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.ResultSetMetaData;
public class OneResultDemo {
   public static void main(String[] args) {
      Connection con = null;
      PreparedStatement ps = null;
      Statement st = null;
      ResultSet rs = null;
      try {
         con = DriverManager.getConnection("jdbc:mysql://localhost:3306/web?useSSL=false", "root", "123456");
         String query = "select *from DemoTable " + " limit 1";
         st = con.createStatement();
         rs = st.executeQuery(query);
         while (rs.next()) {
            System.out.println("Id=" + rs.getInt("Id"));
            System.out.println("Name=" + rs.getString("Name"));
         }
      }
      catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Output

This will produce the following output −

Id=101
Name=Chris

Updated on: 26-Feb-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements