Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Display MySQL Table Values Using Java



For this, you can use the ResultSet concept. For connection, we will be using the MySQL JDBC Driver.

Let us create a table −

Example

mysql> create table demo87
   -> (
   -> name varchar(20),
   -> age int
   -> )
   -> ;
Query OK, 0 rows affected (0.62

Insert some records into the table with the help of insert command −

Example

mysql> insert into demo87 values('John',21);
Query OK, 1 row affected (0.15

mysql> insert into demo87 values('David',23);
Query OK, 1 row affected (0.12

mysql> insert into demo87 values('Bob',22);
Query OK, 1 row affected (0.16

Display records from the table using select statement −

Example

mysql> select *from demo87;

This will produce the following output −

Output

+-------+------+

| name  | age  |

+-------+------+

| John  |   21 |

| David |   23 |

| Bob   |   22 |

+-------+------+

3 rows in set (0.00 sec)

Following is the Java code to display table values in MySQL −

Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;

import com.mysql.jdbc.Statement;

public class TableValuesDemo {
   public static void main(String[] args) {
      Connection con = null;
      Statement statement = null;
      try {
         HashMap hm = new HashMap<>();
         Class.forName("com.mysql.jdbc.Driver");
         con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sampledatabase", "root", "123456");
         statement = (Statement) con.createStatement();
         String sql;
         sql = "select *from demo87";
         ResultSet resultSet = statement.executeQuery(sql);
         while (resultSet.next()) {
         hm.put(resultSet.getString("name"), resultSet.getInt("age"));
      }
      System.out.println(hm);

      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

This will produce the following output −

Output

{Bob=22, John=21, David=23}

Following is the snapshot of sample output −

Updated on: 2020-12-11T05:50:52+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements