数据表结构如下:
CREATE TABLE `demo` ( `id` int(11) DEFAULT NULL, `name` varchar(32) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8
并且在demo表中插入了5条记录:
INSERT INTO demo VALUES (1, 'alan'), (2, 'mike'), (3, 'lucy'), (4, 'jack'), (5, 'mary');
编写Java代码获取到所有数据,并通过while循环遍历打印出所有的数据,代码如下:
@Test public void testResultSet() throws Exception { // 获取值 Properties properties = new Properties(); properties.load(new FileInputStream("src\\mysql.properties")); String user = properties.getProperty("user"); String password = properties.getProperty("password"); String dirver = properties.getProperty("dirver"); String url = properties.getProperty("url"); // 注册驱动 Class.forName(dirver); // 得到连接和Statement Connection connection = DriverManager.getConnection(url, user, password); Statement statement = connection.createStatement(); // 组织SQL String sql = "select * from demo"; // 执行SQL获得结果集 ResultSet resultSet = statement.executeQuery(sql); // 遍历结果集 while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); System.out.println(id + "\t" + name); } // 关闭连接 resultSet.close(); statement.close(); connection.close(); }
得到如下结果: