jdbc---查询语句的使用(executeQuery)

package com.syy;

import domain.student;

import java.sql.*;
import java.util.ArrayList;

public class JdbcDemo3 {

public static void main(String[] args)throws Exception {
ArrayList<student> stu = getstudent();
for (student stu1 : stu) {
System.out.println(stu1);
}

}

private static ArrayList<student> getstudent() throws SQLException {
ArrayList<student> array = new ArrayList<student>();
Connection con = null;
Statement stat = null;
ResultSet resultSet=null;
try {
//1、加载驱动类
Class.forName("com.mysql.jdbc.Driver");
//2、与数据库建立连接
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db4", "root", "1234");
//3、获取sql语句对象
stat = con.createStatement();
//4、定义sql语句
String sql = "select *from student ";
//通过executeQuery返回结果集
resultSet = stat.executeQuery(sql);
//判断是否有下一个数据---获取下一个元素
// resultSet.next();相当于指针下移
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String grade = resultSet.getString("grade");
System.out.println(id + "\t" + name + "\t" + grade);
//把字段封装成对象
//创建对象
student s = new student();
s.setId(id);
s.setName(name);
s.setGrade(grade);
//把对象添加到集合中
array.add(s);

}


} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.close();
con = null;
}
if (stat != null) {
stat.close();
stat = null;
}
if (resultSet!=null){
resultSet.close();

}

}

return array;
}

}
上一篇:Accessing the Deep Web: A Survey


下一篇:纯JDBC查询数据库并转换为对应实体类的List集合