处理结果集刚开始位置为第一条数据上面,并不是第一条数据,当执行resultSet.next()时,才指向第一条数据,resultSet.getString()获取表中的数据,从第一列开始。当不为空时返回true,否则返回false,知道遍历到表的最后一行的下一个为空时,返回false,执行结束。(查询时列数从1开始,并不是从0开始),到最后结果集要关闭。
package JDBCTest;
import java.io.*;
import java.sql.*;
import java.util.Properties;
public class JDBCTest04 {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
FileReader fileReader = new FileReader("Study/src/JDBCTest/JDBCTest04.properties");
Properties properties = new Properties();
properties.load(fileReader);
fileReader.close();
String url = (String)properties.get("url");
String user = (String)properties.get("user");
String password = (String)properties.get("password");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url, user, password);
statement = connection.createStatement();
String sql = "select no,age,name from t_student";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
String no = resultSet.getString("no");
String age = resultSet.getString("age");
String name = resultSet.getString("name");
System.out.println(" no: "+no + " age: "+age+" name: "+name);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
}
}
导入Mysq的jar包
第一步:
第二步:
第三步: