Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Is there a way to make a list from a MySQL table in Java?
Yes, for this, use the concept of ArrayList in Java. The syntax is as follows −
ArrayList<ArrayList<yourDataType>> anyVariableName= new ArrayList<ArrayList<yourDataType>>();
Let us create a table −
mysql> create table demo10 −> ( −> id int not null auto_increment primary key, −> name varchar(20) −> ); Query OK, 0 rows affected (2.19 sec)
Insert some records into the table with the help of insert command −
mysql> insert into demo10(name) values('John');
Query OK, 1 row affected (0.23 sec)
mysql> insert into demo10(name) values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into demo10(name) values('David');
Query OK, 1 row affected (0.13 sec)
Display records from the table using select statement −
mysql> select *from demo10;
This will produce the following output −
+----+-------+ | id | name | +----+-------+ | 1 | John | | 2 | Bob | | 3 | David | +----+-------+ 3 rows in set (0.00 sec)
Example
Following is the Java code −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import com.mysql.jdbc.Statement;
public class ListInListDemo {
public static void main(String[] args) {
Connection con = null;
Statement statement = null;
try {
ArrayList<ArrayList<String>> outer = new ArrayList<ArrayList<String>>();
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 demo10";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
ArrayList<String> inner = new ArrayList<String>();
inner.add(resultSet.getString("name"));
outer.add(inner);
}
System.out.println("The name are as follows:");
for (int i = 0; i < outer.size(); i++) {
System.out.println(outer.get(i));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
This will produce the following output −
The name are as follows: [John] [Bob] [David]
The snapshot is as follows −

Advertisements