- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
Advertisements