JavaEE项目学习——JDBC入门基础知识

环境

1.Eclipse Java Photon

2.MySQL 8.0(DBMS可用自带的黑框框也可用Navicat 12,不过是收费的)

3.JDK 1.8.0

4.jar包:mysql_connector_java 8.0.13

(由于我的环境都是自己装的(船新版本,过程中遇到了很多小麻烦Orz),过程中需要的mysql_connector_java可从MySQL官网下载,不明白的可以参考这篇博客:如何在MySQL官网下载jar包附8.0jar包百度云地址)

(jar包的使用:包放在新建文件夹lib里,右键jar包--构建路径--配置构建路径)

 

JDBC概述

Java DataBase Connection  Java数据库连接,实现Java代码与数据库之间的数据交互。

1.将Java代码中的数据保存到数据库

2.将数据库中的数据查询到Java代码

JDBC步骤

1.建立连接(数据库服务器ip,数据库port,用户名,密码)

2.准备需要执行的SQL指令

3.通过数据库连接加载SQL指令

4.执行SQL指令,获取执行结果

5.处理结果

6.关闭连接

 

理解并记住这六个步骤我们就可以开始实现JDBC了。

首先我们需要自己建立一个数据库,这里我使用MySQL建了两个数据库:db_qzone和db_sims。

create table tb_users(
   qq varchar(11) primary key,
   pwd varchar(16) not null,
   nick varchar(20) not null,
   sex char(2) not null,
   age int,
   remark varchar(100)
);

create table tb_articles(
   art_id int primary key auto_increment,
   art_title varchar(50) not null,
   art_content text not null,
   art_time datetime not null,
   art_type char(4) not null,
   art_qq varchar(11) not null,
   constraint FK_ARTICLES_USERS foreign key(art_qq)references tb_users(qq)
);

create table tb_albums(
   album_id int primary key auto_increment,
   album_name varchar(20) not null,
   album_desc varchar(200),
   album_time datetime not null,
   album_cover varchar(100),
   album_qq varchar(11) not null,
   constraint FK_ALBUMS_USERS foreign key(album_qq)references tb_users(qq)
);

create table tb_photos(
   photo_id int primary key auto_increment,
   photo_url varchar(100) not null,
   photo_desc varchar(40),
   photo_time datetime not null,
   photo_aid int not null,
   constraint FK_PHOTOS_ALBUMS foreign key(photo_aid)references tb_albums(album_id)
);


create table tb_students(
   stu_num char(5) primary key,
   stu_name varchar(20) not null,
   stu_sex char(2) not null,
   stu_age int not null,
   stu_tel char(11) not null unique
);

create table tb_courses(
   course_id char(8) primary key,
   course_name varchar(50) not null,
   course_score float not null
);

create table tb_student_course(
   snum char(5) not null,
   cid char(8) not null,
   primary key(snum,cid),
   constraint FK_SC_STUDENT foreign key(snum) references tb_students(stu_num),
   constraint FK_SC_COURSE foreign key(cid) references tb_courses(course_id)
);


insert into tb_students(stu_num,stu_name,stu_sex,stu_age,stu_tel)
values('stu1','joker','GG',21,'17630642952');
insert into tb_students(stu_num,stu_name,stu_sex,stu_age,stu_tel)
values('stu2','aoker','GG',21,'17630642953');
insert into tb_students(stu_num,stu_name,stu_sex,stu_age,stu_tel)
values('stu3','boker','GG',21,'17630642954');
insert into tb_students(stu_num,stu_name,stu_sex,stu_age,stu_tel)
values('stu4','coker','GG',21,'17630642955');
insert into tb_students(stu_num,stu_name,stu_sex,stu_age,stu_tel)
values('stu5','doker','GG',21,'17630642956');


insert into tb_courses(course_id,course_name,course_score)
values('course1','math',138.8);
insert into tb_courses(course_id,course_name,course_score)
values('course2','english',139.8);
insert into tb_courses(course_id,course_name,course_score)
values('course3','chinese',138.9);

insert into tb_student_course(snum,cid)
values('stu1','course1');
insert into tb_student_course(snum,cid)
values('stu2','course3');
insert into tb_student_course(snum,cid)
values('stu3','course2');

嵌套查询:
select * from tb_courses where course_id in (select cid from tb_student_course where snum='stu1');

效果部分截图如下:

JavaEE项目学习——JDBC入门基础知识_第1张图片

JavaEE项目学习——JDBC入门基础知识_第2张图片

建好数据库以后我们就要实现Java代码对数据库的操作了。

 

JDBC实现

JavaEE项目学习——JDBC入门基础知识_第3张图片

( 名词解释:DAO: data access object数据访问对象 DTO : Data Transfer Object数据传输对象 utils:工具集)

1.创建Java项目“jdbc_0100”

2.在项目的src中创建名为“com.joker.jdbc.dto”的package

3.在“com.joker.jdbc.dto”包中创建名为“Student”类

  PS:当我们需要对某张数据表进行操作的时候,首先要创建一个类(实体类/JavaBean),用于存储从数据表中查询出的记录。所以创建实体类要求如下:(“要想调用类的方法就需要类的对象”--脑子里又冒出了这句话)

* 1.类中属性的个数和类型要与对应的数据表保持一致

* 2.提供无参构造器 和 带有所有参数的构造器

* 3.提供所有属性的get和set方法

* 4.重写toString方法:右键--source--Generate toString--OK

package com.joker.jdbc.dto;

import java.io.Serializable;

/**
 * 1.类中属性的个数和类型要与对应的数据表保持一致
 * 2.提供无参构造器 和 带有参数的构造器
 * 3.提供所有属性的get和set方法
 * 4.重写toString方法:右键--source--Generate toString--OK
 * 
 * 5.实现序列化接口
 * 6.重写equals方法
 * 7.重写hashcode方法
 * @author 25213
 *
 */

public class Student {
	
	private String stuNum;
	private String stuName;
	private String stuSex;
	private int stuAge;
	private String stuTel;
	
	@Override
	public String toString() {
		return "Student [stuNum=" + stuNum + ", stuName=" + stuName + ", stuSex=" + stuSex + ", stuAge=" + stuAge
				+ ", stuTel=" + stuTel + "]";
	}

	public Student() {
	}

	public Student(String stuNum, String stuName, String stuSex, int stuAge, String stuTel) {
		super();
		this.stuNum = stuNum;
		this.stuName = stuName;
		this.stuSex = stuSex;
		this.stuAge = stuAge;
		this.stuTel = stuTel;
	}

	public String getStuNum() {
		return stuNum;
	}

	public void setStuNum(String stuNum) {
		this.stuNum = stuNum;
	}

	public String getStuName() {
		return stuName;
	}

	public void setStuName(String stuName) {
		this.stuName = stuName;
	}

	public String getStuSex() {
		return stuSex;
	}

	public void setStuSex(String stuSex) {
		this.stuSex = stuSex;
	}

	public int getStuAge() {
		return stuAge;
	}

	public void setStuAge(int stuAge) {
		this.stuAge = stuAge;
	}

	public String getStuTel() {
		return stuTel;
	}

	public void setStuTel(String stuTel) {
		this.stuTel = stuTel;
	}
	
	
	
}

(这个代码就是写完五个属性以后右键快捷键自动生成的)

测试一下:

package com.joker.jdbc.dto;


//测试Student类是否正确
public class Test {
	public static void main(String[] args) {
		Student s = new Student("stu10","zoker","GG",28,"15858585588");
		System.out.println(s);
	}
}

 

4.在项目的src中创建名为“com.joker.jdbc.dao”的package

5.在“com.joker.jdbc.dao”包中创建名为“StudentDAO”类,对学生表的所有数据库操作都在此类中完成。【对数据库中每个操作都单独定义一个方法完成】

6.JDBC实现操作

JavaEE项目学习——JDBC入门基础知识_第4张图片

7.测试

注意在第二步准备SQL语句过程中时注意SQL注入问题:

JDBC预编译机制解决SQL注入问题

SQL注入

在SQL语句采用字符串拼接传递参数的情况,会出现因为参数值得改变导致SQL语义发生改变的情况。

预编译

1.SQL指令中需要参数一律用?表示

2.如果语句中有?,则使用” PreparedStatement ps = conn.prepareStatement(sql);”加载SQL指令,不再使用“Statement stmt = conn.createStatement();

 

代码:

StudentDAO.java

package com.joker.jdbc.dao;

import java.util.*;
import java.util.List;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.sql.*;

import com.joker.jdbc.dto.Student;
import com.joker.jdbc.utils.DBManager;

public class StudentDAO {
	//1.添加操作
	public boolean insertStudent(Student s) {
		boolean flag = false;
		try {
			Connection conn = DBManager.getConn();//1.创建对象实现类的方法--连接数据库
			
			String sql = "insert into tb_students(stu_num,stu_name,stu_sex,stu_age,stu_tel) values(?,?,?,?,?)";//2.准备SQL语句
			
			PreparedStatement ps = conn.prepareStatement(sql);//3.对SQL语句预处理
			ps.setString(1, s.getStuNum());
			ps.setString(2, s.getStuName());
			ps.setString(3, s.getStuSex());
			ps.setInt(4, s.getStuAge());
			ps.setString(5, s.getStuTel());//4.对?赋值
			
			int i = ps.executeUpdate();//5.执行更新返回整型的结果表示数据库几行受影响
			
			flag = i>0?true:false;//6.处理结果
			
			conn.close();//7.关闭连接
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
	//2.删除操作:根据学号删除学生信息
	public boolean deleteStudent(String stuNum) {
		boolean flag=false;
		
		try {
			Connection conn = DBManager.getConn();
			String sql = "delete from tb_students where stu_num=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, stuNum);
			int i = ps.executeUpdate();
			flag = i>0?true:false;
			conn.close();	
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return flag;
	}
	
	//3.修改操作:根据学号修改姓名、性别、年龄、电话
	public boolean updateStudent(Student s) {
		boolean flag = false;
		
		try {
			Connection conn = DBManager.getConn();
			String sql = "update tb_students set stu_name=?,stu_sex=?,stu_age=?,stu_tel=? where stu_num=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, s.getStuName());
			ps.setString(2, s.getStuSex());
			ps.setInt(3, s.getStuAge());
			ps.setString(4, s.getStuTel());
			ps.setString(5, s.getStuNum());
			int i = ps.executeUpdate();
			flag = i>0?true:false;
			conn.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return flag;
	}
	
	//4.查询1:根据学号查询学生信息
	public Student queryStudent(String stuNum) {
		Student s = null;
		
		try {
			Connection conn = DBManager.getConn();
			String sql = "select * from tb_students where stu_num=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, stuNum);
			ResultSet rs = ps.executeQuery();//结果集存参
			if(rs.next()) {
				String stuName = rs.getString("stu_name");//把结果暂存
				String stuSex = rs.getString("stu_sex");
				int stuAge = rs.getInt("stu_age");
				String stuTel = rs.getString("stu_tel");
				s = new Student(stuNum, stuName, stuSex, stuAge, stuTel);
			}
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return s;
	}
	
	//5.查询2:查询所有学生(只装Student的集合)
	public List allStudent() {
		List stus = new ArrayList();
		
		try {
			Connection conn = DBManager.getConn();
			String sql = "select * from tb_students";
			PreparedStatement ps = conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			while(rs.next()) {
				String stuNum = rs.getString("stu_num");
				String stuName =rs.getString("stu_name");
				String stuSex = rs.getString("stu_sex");
				int stuAge = rs.getInt("stu_age");
				String stuTel = rs.getString("stu_tel");
				
				Student stu = new Student(stuNum, stuName, stuSex, stuAge, stuTel);
				stus.add(stu);
			}
			conn.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return stus;
	}
	
	//6.查询3:根据性别查询学生信息
	public List allStudent(String stuSexx) {
		List stus = new ArrayList();
		
		try {
			Connection conn = DBManager.getConn();
			String sql = "select * from tb_students where stu_sex=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, stuSexx);
			ResultSet rs = ps.executeQuery();
			while(rs.next()) {
				String stuNum = rs.getString("stu_num");
				String stuName = rs.getString("stu_name");
				String stuSex = rs.getString("stu_sex");
				int stuAge = rs.getInt("stu_age");
				String stuTel = rs.getString("stu_tel");
				Student s6 = new Student(stuNum, stuName, stuSex, stuAge, stuTel);
				stus.add(s6);
			}
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return stus;
	}

	//7.查询4:根据年龄区间查询学生信息
	public List allStudent(int minn,int maxx) {
		List stus = new ArrayList();
		
		try {
			
			Connection conn = DBManager.getConn();
			String sql = "select * from tb_students where stu_age between ? and ?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, minn);
			ps.setInt(2, maxx);
			ResultSet rs = ps.executeQuery();
			while(rs.next()) {
				String stuNum = rs.getString("stu_num");
				String stuName = rs.getString("stu_name");
				String stuSex = rs.getString("stu_sex");
				int stuAge = rs.getInt("stu_age");
				String stuTel = rs.getString("stu_tel");
				Student s7 =new Student(stuNum, stuName, stuSex, stuAge, stuTel);
				stus.add(s7);
			}
			conn.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return stus;
	}
}

DAManager.java

package com.joker.jdbc.utils;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBManager {

	private static final String DRIVER="com.mysql.cj.jdbc.Driver";
	private static final String URL="jdbc:mysql://localhost:3306/db_sims";
	private static final String USERNAME="root";
	private static final String PASSWORD="123456";
	
	static {
		try {
			Class.forName(DRIVER);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConn() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
}

 

测试代码 Test.java

package com.joker.jdbc.dao;

import java.util.*;

import com.joker.jdbc.dto.Student;

public class Test {
	public static void main(String[] args) {
		StudentDAO sdao = new StudentDAO();

//		测试插入		
//		Student s1 = new Student("stu9","qoker","MM",18,"12123232233");//有参构造
//		boolean flag1 = sdao.insertStudent(s1);
//		System.out.println(flag1);

//		测试删除:根据学号删除学生信息
//		boolean flag2 = sdao.deleteStudent("stu9");
//		System.out.println(flag2);
		
//		测试修改:根据学号修改姓名、性别、年龄、电话		
//		Student s3 = new Student("stu2","zoker","MM",17,"16868686688");
//		boolean flag3 = sdao.updateStudent(s3);
//		System.out.println(flag3);

//		测试查询:根据学号查询学生信息
//		Student s4 = sdao.queryStudent("stu1");
//		System.out.println(s4);
		
//		测试查询2:查询所有学生(只装Student的集合)
//		List stus2 = sdao.allStudent();
//		for (Student s5 : stus2) {//foreach遍历
//			System.out.println(s5);
//		}

//		测试查询3:输入性别查询学生信息
//		List stus3 = sdao.allStudent("MM");
//		for (Student s6 : stus3) {
//			System.out.println(s6);
//		}
		
//		测试查询4:输入年龄范围查询学生信息
//		List stus4 = sdao.allStudent(20, 30);
//		for (Student s7 : stus4) {
//			System.out.println(s7);
//		}
		
	}
	
}

 

其中遇到的一些问题以及解决方法:

mysql的时区错误问题: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one

Loading class `com.mysql.jdbc.Driver'. This is deprecated警告处理,jdbc更新处

如何在MySQL官网下载jar包附8.0jar包百度云地址

 

一些知识点:

数据库操作中 pstmt.setString(1,id) ; 是什么意思 那个“1”指什么详解

ResultSet类的基本解读

Java的常见术语(PO/POJO/VO/BO/DAO/DTO)

Java中三种for循环之间的对比

 

 



以下代码加了些注释,以备将来温习所用,代码和上面是一样的,可忽略~

DBManager.java

package com.joker.jdbc.utils;

import java.sql.*;

public class DBManager {

	//设置成常量避免被修改
	private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
	private static final String URL = "jdbc:mysql://localhost:3306/db_qzone";
	private static final String USERNAME = "root";
	private static final String PASSWORD = "123456";
	
	
	//驱动只需加载一次,静态块只执行一次
	static {
		try {
			Class.forName(DRIVER);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	//创建连接
	public static Connection getConn() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	
}

Student.java

package com.joker.jdbc.dto;

import java.io.Serializable;

/**
 * 1.类中属性的个数和类型要与对应的数据表保持一致
 * 2.提供无参构造器 和 带有参数的构造器
 * 3.提供所有属性的get和set方法
 * 4.重写toString方法:右键--source--Generate toString--OK
 * 
 * 5.实现序列化接口
 * 6.重写equals方法
 * 7.重写hashcode方法
 * @author 25213
 *
 */

public class Student {
	
	private String stuNum;
	private String stuName;
	private String stuSex;
	private int stuAge;
	private String stuTel;
	
	@Override
	public String toString() {
		return "Student [stuNum=" + stuNum + ", stuName=" + stuName + ", stuSex=" + stuSex + ", stuAge=" + stuAge
				+ ", stuTel=" + stuTel + "]";
	}

	public Student() {
	}

	public Student(String stuNum, String stuName, String stuSex, int stuAge, String stuTel) {
		super();
		this.stuNum = stuNum;
		this.stuName = stuName;
		this.stuSex = stuSex;
		this.stuAge = stuAge;
		this.stuTel = stuTel;
	}

	public String getStuNum() {
		return stuNum;
	}

	public void setStuNum(String stuNum) {
		this.stuNum = stuNum;
	}

	public String getStuName() {
		return stuName;
	}

	public void setStuName(String stuName) {
		this.stuName = stuName;
	}

	public String getStuSex() {
		return stuSex;
	}

	public void setStuSex(String stuSex) {
		this.stuSex = stuSex;
	}

	public int getStuAge() {
		return stuAge;
	}

	public void setStuAge(int stuAge) {
		this.stuAge = stuAge;
	}

	public String getStuTel() {
		return stuTel;
	}

	public void setStuTel(String stuTel) {
		this.stuTel = stuTel;
	}
	
	
	
}

StudentDAO.java

package com.joker.jdbc.dao;

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

import javax.swing.plaf.basic.BasicBorders.ToggleButtonBorder;

import org.omg.CORBA.COMM_FAILURE;

import com.joker.jdbc.dto.Student;
import com.joker.jdbc.dto.test;
import com.joker.jdbc.utils.DBManager;

public class StudentDAO {
	
	//对数据库中的每个操作单独定义一个方法
	
	//1.添加操作:将Java代码中的学生信息保存到数据库 db_qzone/tb_students
//	public boolean insertStudent(String num,String name,String sex,int age,String tel) {
//		
//	}
	public boolean insertStudent(Student s) {
		boolean b = false;
		//捕捉异常
		try {
			
			/*
			//1.建立连接(java和数据库是两个不同的软件所以需要"适配器"--JDBC驱动(手机充电的例子))
			//a.加载JDBC驱动jar文件(不同的数据库有不同的驱动)(将jar包添加到项目中,通过反射机制加载驱动)
			Class.forName("com.mysql.jdbc.Driver");
			//b.通过驱动管理器创建连接
//			DriverManager.getConnection(url, user, password);
			//jdbc:mysql://ip:localhost:127.0.0.1
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_qzone", "root", "123456");
			*/
			
			Connection conn = DBManager.getConn();
			
			//2.准备SQL语句
			//String sql = "insert into tb_students(stu_num,stu_name,stu_sex,stu_age,stu_tel) values('"+s.getStuNum()+"','"+s.getStuName()+
			//		"','"+s.getStuSex()+"',"+s.getStuAge()+",'"+s.getStuTel()+"')";
			String sql = "insert into tb_students(stu_num,stu_name,stu_sex,stu_age,stu_tel) values(?,?,?,?,?)";
			
			//3.通过连接获取SQL语句"加载器"
			//Statement stmt = conn.createStatement();//statement就是"加载器",但通过这种方式赋值可能会改变sql语句的语意,故使用preparestatement加载器
			//使用preparedstatement加载器,先预处理SQL语句再对?赋值
			PreparedStatement ps = conn.prepareStatement(sql);
			
			//3.2 SQL语句加载之后给SQL中的?赋值
			ps.setString(1, s.getStuNum());
			ps.setString(2, s.getStuName());
			ps.setString(3, s.getStuSex());
			ps.setInt(4, s.getStuAge());
			ps.setString(5, s.getStuTel());
			
			//4.加载执行SQL语句
			//int i = stmt.executeUpdate(sql);//增删改一律用executeUpdate查询用executeQuery
			
			int i = ps.executeUpdate();
			
			
			//5.处理结果
			b = i>0?true:false;
			
			//6.关闭连接
			conn.close();
			
		} catch (Exception e) {
			e.printStackTrace();//打印错误信息
		}
		
		return b;
	}

	//2.删除操作:根据主键删除一条记录
	public boolean deleteStudent(String stuNum) {
		boolean b = false;
		try {
			/*
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_qzone", "root", "123456");
//			*/
			
			Connection conn = DBManager.getConn();
			
//			String sql = "delete from tb_students where stu_num='"+stuNum+"'";
//			Statement stmt = conn.createStatement();
//			int i = stmt.executeUpdate(sql);
			String sql = "delete from tb_students where stu_num=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			//给SQL指令中的?赋值
			ps.setString(1, stuNum);//给第一个问号赋值
			int i = ps.executeUpdate();
			b = i>0?true:false;
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	}
	
	//3.修改操作:根据学号修改姓名、性别、年龄和电话
	public boolean updateStudent(Student s) {
		boolean b = false;
		try {
			Connection conn = DBManager.getConn();
			String sql = "update tb_students set stu_name=?,stu_sex=?,stu_age=?,stu_tel=? where stu_num=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, s.getStuName());
			ps.setString(2, s.getStuSex());
			ps.setInt(3, s.getStuAge());
			ps.setString(4, s.getStuTel());
			ps.setString(5, s.getStuNum());
			
			int i = ps.executeUpdate();
			b = i>0?true:false;
			conn.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	}
	
	//2.查询1:根据学生的学号查询一个学生信息
	public Student queryStudent(String stuNum) {
		Student s = null;
		try {
			Connection conn = DBManager.getConn();
			String sql = "select * from tb_students where stu_num=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, stuNum);
			//如果SQL语句是查询操作
			ResultSet rs = ps.executeQuery();//结果集临时的容器
			if(rs.next()) {
				String stuName = rs.getString("stu_name");
				String stuSex = rs.getString("stu_sex");
				int stuAge = rs.getInt("stu_age");
				String stuTel = rs.getString("stu_tel");
				s = new Student(stuNum, stuName, stuSex, stuAge, stuTel);
			}
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}
	
	
	//3.查询2:查询所有学生(只装Student的集合)
	public List listStudents() {
		List stus = new ArrayList();
		try {
			Connection conn = DBManager.getConn();
			String sql = "select * from tb_students";
			//Statement stmt = conn.createStatement();
			//ResultSet rs = stmt.executeQuery(sql);
			PreparedStatement ps = conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			while(rs.next()) {
				String stuNum = rs.getString("stu_num");
				String stuName = rs.getString("stu_name");
				String stuSex = rs.getString("stu_sex");
				int stuAge = rs.getInt("stu_age");
				String stuTel = rs.getString("stu_tel");
				
				Student stu = new Student(stuNum, stuName, stuSex, stuAge, stuTel);
				stus.add(stu);
				
			}
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stus;
	}
	
	
	//查询3:根据性别查询学生信息
	public List listStudents(String stu_sex) {
		List stus = new ArrayList();
		try {
			Connection conn = DBManager.getConn();
			String sql = "select * from tb_students where stu_sex=?";
			//Statement stmt = conn.createStatement();
			//ResultSet rs = stmt.executeQuery(sql);
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, stu_sex);
			ResultSet rs = ps.executeQuery();
			while(rs.next()) {
				String stuNum = rs.getString("stu_num");
				String stuName = rs.getString("stu_name");
				String stuSex = rs.getString("stu_sex");
				int stuAge = rs.getInt("stu_age");
				String stuTel = rs.getString("stu_tel");
				
				Student stu = new Student(stuNum, stuName, stuSex, stuAge, stuTel);
				stus.add(stu);
				
			}
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stus;
	}
	
	
	//查询4:根据年龄查询学生信息
	public List listStudents(int min,int max) {
		List stus = new ArrayList();
		try {
			Connection conn = DBManager.getConn();
			String sql = "select * from tb_students where stu_age between ? and ?";
			//Statement stmt = conn.createStatement();
			//ResultSet rs = stmt.executeQuery(sql);
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, min);
			ps.setInt(2, max);
			ResultSet rs = ps.executeQuery();
			while(rs.next()) {
				String stuNum = rs.getString("stu_num");
				String stuName = rs.getString("stu_name");
				String stuSex = rs.getString("stu_sex");
				int stuAge = rs.getInt("stu_age");
				String stuTel = rs.getString("stu_tel");
				
				Student stu = new Student(stuNum, stuName, stuSex, stuAge, stuTel);
				stus.add(stu);
				
			}
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stus;
	}
	
}

 

 

(太惨了,期末就要到了,为了各种各样作业就先搞起这个了Orz 不过有人带着学比自己去学节省了太多时间 已经下定决心考研所以每一分钟都显得格外珍贵  今天正是19级研究生初试,也是冬至,希望他们会有好的结果,也希望来年此时我也能如愿以偿吧! 山不过来,我便过去!)

你可能感兴趣的:(笔记,Java,JDBC)