其他分享
首页 > 其他分享> > jdbc---查询语句的使用(executeQuery)

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;
}

}

标签:stat,jdbc,ArrayList,executeQuery,resultSet,---,student,null,con
来源: https://www.cnblogs.com/syy2017/p/14093121.html