有没有办法在 Java 中从一个 MySQL 表创建一个列表?
是的,为此,请使用 Java 中的 ArrayList 概念。语法如下所示 −
ArrayList<ArrayList<yourDataType>> anyVariableName= new ArrayList<ArrayList<yourDataType>>();
让我们创建一个表 −
mysql> create table demo10 −> ( −> id int not null auto_increment primary key, −> name varchar(20) −> ); Query OK, 0 rows affected (2.19 sec)
使用插入命令向表中插入一些记录 −
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)
使用 select 语句显示表中的记录 −
mysql> select *from demo10;
这将产生以下输出 −
+----+-------+ | id | name | +----+-------+ | 1 | John | | 2 | Bob | | 3 | David | +----+-------+ 3 rows in set (0.00 sec)
示例
以下为 Java 代码 −
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://127.0.0.1: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(); } } }
输出
这将产生以下输出 −
The name are as follows: [John] [Bob] [David]
快照如下所示 −
广告