处理结果集刚开始位置为第一条数据上面,并不是第一条数据,当执行resultSet.next()时,才指向第一条数据,resultSet.getString()获取表中的数据,从第一列开始。当不为空时返回true,否则返回false,知道遍历到表的最后一行的下一个为空时,返回false,执行结束。(查询时列数从1开始,并不是从0开始),到最后结果集要关闭。

    1. package JDBCTest;
    2. import java.io.*;
    3. import java.sql.*;
    4. import java.util.Properties;
    5. public class JDBCTest04 {
    6. public static void main(String[] args) {
    7. Connection connection = null;
    8. Statement statement = null;
    9. ResultSet resultSet = null;
    10. try {
    11. FileReader fileReader = new FileReader("Study/src/JDBCTest/JDBCTest04.properties");
    12. Properties properties = new Properties();
    13. properties.load(fileReader);
    14. fileReader.close();
    15. String url = (String)properties.get("url");
    16. String user = (String)properties.get("user");
    17. String password = (String)properties.get("password");
    18. Class.forName("com.mysql.jdbc.Driver");
    19. connection = DriverManager.getConnection(url, user, password);
    20. statement = connection.createStatement();
    21. String sql = "select no,age,name from t_student";
    22. resultSet = statement.executeQuery(sql);
    23. while (resultSet.next()) {
    24. String no = resultSet.getString("no");
    25. String age = resultSet.getString("age");
    26. String name = resultSet.getString("name");
    27. System.out.println(" no: "+no + " age: "+age+" name: "+name);
    28. }
    29. } catch (SQLException e) {
    30. e.printStackTrace();
    31. } catch (ClassNotFoundException e) {
    32. e.printStackTrace();
    33. }catch (FileNotFoundException e) {
    34. e.printStackTrace();
    35. } catch (IOException e) {
    36. e.printStackTrace();
    37. }finally {
    38. if (resultSet != null) {
    39. try {
    40. resultSet.close();
    41. } catch (SQLException e) {
    42. e.printStackTrace();
    43. }
    44. if (statement != null) {
    45. try {
    46. statement.close();
    47. } catch (SQLException e) {
    48. e.printStackTrace();
    49. }
    50. if (connection != null) {
    51. try {
    52. connection.close();
    53. } catch (SQLException e) {
    54. e.printStackTrace();
    55. }
    56. }
    57. }
    58. }
    59. }
    60. }
    61. }

    导入Mysq的jar包
    第一步:
    image.png

    第二步:
    image.png

    第三步:
    image.png