目标:掌握Java数据库编程

内容:

学生选课系统包括如下数据库表

  • 学生表:Student(Sno,Sname,Ssex,Sage,Sdept)
  • 课程表:Course(Cno,Cname,Ccredit)
  • 学生选课表:SC(Sno,Cno,Grade)

在课堂上,老师以学生管理功能为例用Java实现了对学生记录的增、删、改、查操作。请仿照此例,用Java实现对课程和学生选课记录的增、删、改、查操作。

程序实现代码:

Course.java;

CourseManger.java;

CourseTableCreator.java;

DatabaseManager.java;

Student.java;

StudentManager.java;

StudentTableCreator.java;

SelectCourse.java;

SelectCourseManager.java;

scTableCreator.java

代码1:Course.java

public class Course {

       private   int      Cno;
private String Cname;
private int Ccredit; public void setNo(int Cno){
this.Cno = Cno;
}
public void setName(String Cname){
this.Cname = Cname;
}
public void setCredit(int Ccredit){
this.Ccredit = Ccredit;
} public int getNo(){
return Cno;
}
public String getName(){
return Cname;
}
public int getCredit(){
return Ccredit;
}
public String toString(){
return "Cno: "+Cno+"\tCname: "+Cname+"\tCcredit: "+Ccredit;
}
}

代码2:CourseManager.java

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.util.ArrayList; public class CourseManager {
private Connection cn ;
private Statement stmt;
private PreparedStatement prepStmt; public CourseManager(){
cn = new DatabaseManager().openConnection();
} public void addCourse(Course course){
try{
if(cn!=null){
String query = "insert into course(Cno ,Cname ,Ccredit ) values(? ,? ,? )";
prepStmt = cn.prepareStatement(query);
prepStmt.setInt(1 ,course.getNo());
prepStmt.setString(2 ,course.getName());
prepStmt.setInt(3 ,course.getCredit());
prepStmt.executeUpdate();
}
} catch (Exception e){
System.out.println("create CourseManager error:"+e);
}
} public void deleteCourse(Course course){
try{
if(cn!=null){
String query = "delete form course where Cno =?";
prepStmt = cn.prepareStatement(query);
prepStmt.setInt(1 ,course.getNo());
prepStmt.executeUpdate();
}
} catch (Exception e){
System.out.println("delet course error:"+e);
}
} public void updateCourse(Course course){
try{
if(cn!= null){
String query = "update course set Cno=?,Cname=?,Ccredit=? ";
prepStmt = cn.prepareStatement(query);
prepStmt.setInt(1 ,course.getNo());
prepStmt.setString(2 ,course.getName());
prepStmt.setInt(3 ,course.getCredit());
prepStmt.executeUpdate();
}
}catch (Exception e){
System.out.println("update course error:"+e);
}
} public ArrayList<Course> queryCourse(){
ArrayList<Course> courses = new ArrayList<Course>();
Course course;
try{
if(cn!=null){
stmt = cn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM course");
while(rs.next()){
course = new Course();
course.setNo(rs.getInt("Cno"));
course.setName(rs.getString("Cname"));
course.setCredit(rs.getInt("Ccredit"));
courses.add(course);
}
}
} catch (Exception e){
System.out.println("query course error:"+e);
}
return courses;
}
public void closeConnection(){
try{
stmt.close();
prepStmt.close();
cn.close();
} catch (Exception e){
System.out.println("close connection error:"+e);
}
}
}

代码3:CourseTableCreator.java

import java.sql.*;

public class CourseTableCreator {
private Connection cn;
private Statement stmt;
private PreparedStatement prepStmt; public CourseTableCreator() {
cn = new DatabaseManager().openConnection();
} public void dropTable() {
try {
if (cn != null) {
stmt = cn.createStatement();
String qurey = "drop table course";
stmt.execute(qurey);
System.out.println("drop table course");
}
} catch (Exception e) {
System.out.println("drop table course error:" + e);
}
} public void createTable() {
try {
if (cn != null) {
String qurey = "create table course(Cno int PRIMARY KEY,Cname varchar(20),Ccredit int)";
stmt = cn.createStatement();
stmt.execute(qurey);
System.out.println("create table course");
}
} catch (Exception e) {
System.out.println("create table course error: " + e);
}
} public void insertIntRecords() {
try {
if (cn != null) {
String query = "insert into course(Cno ,Cname ,Ccredit) values(?, ?, ?)";
prepStmt = cn.prepareStatement(query);
prepStmt.setInt(1, 1001);
prepStmt.setString(2, "高等数学");
prepStmt.setInt(3, 6);
prepStmt.executeUpdate(); prepStmt.setInt(1, 1002);
prepStmt.setString(2, "java程序设计");
prepStmt.setInt(3, 3);
prepStmt.executeUpdate(); prepStmt.setInt(1, 1003);
prepStmt.setString(2, "通信原理");
prepStmt.setInt(3, 5);
prepStmt.executeUpdate(); prepStmt.setInt(1, 1004);
prepStmt.setString(2, "DSP 原理及其应用");
prepStmt.setInt(3, 3);
prepStmt.executeUpdate(); System.out.println("4 course records has been inserted");
}
} catch (Exception e) {
System.out.println("create table course error:" + e);
}
} public void closeConnection() {
try {
stmt.close();
prepStmt.close();
cn.close();
} catch (Exception e) {
System.out.println("table course close conncetion error:" + e);
}
} public static void main(String[] args) {
// TODO Auto-generated method stub
CourseTableCreator creator = new CourseTableCreator();
creator.dropTable();
creator.createTable();
creator.insertIntRecords();
creator.closeConnection();
} }

代码4:DatabaseManager.java

import java.sql.DriverManager;
import java.sql.Connection; public class DatabaseManager {
private Connection cn;
public Connection openConnection() {
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/javaCourse";
cn=DriverManager.getConnection(url, "root", "manager"); }catch(Exception e){
System.out.println("open databse connection error:"+e);
} return cn;
}
public void closeConnection(){
try{
cn.close();
}catch (Exception e){
System.out.println("close databse connection error:"+e);
}
} }
SelectCourse.java的源代码如下:
public class SelectCourse {
private int Sno;
private int Cno;
private int Grade; public void setStudentNo(int Sno){
this.Sno = Sno;
}
public int getStudentNo(){
return Sno;
}
public void setCourseNo(int Cno){
this.Cno = Cno;
}
public int getCourseNo(){
return Cno;
}
public void setGrade(int Grade){
this.Grade = Grade;
}
public int getGrade(){
return Grade;
}
}

代码5:SelectCourseManager.java

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.util.ArrayList; public class SelectCourseManager {
private Connection cn;
private Statement stmt;
private PreparedStatement prepStmt; public SelectCourseManager(){
cn = new DatabaseManager().openConnection();
} public void addRecord(SelectCourse sc){
try{
if(cn!= null){
String query = "insert into selectCourse(Sno ,Cno ,Grade) values(? ,? ,?)";
prepStmt = cn.prepareStatement(query);
prepStmt.setInt(1 , sc.getStudentNo());
prepStmt.setInt(2 , sc.getCourseNo());
prepStmt.setInt(3 , sc.getGrade());
prepStmt.executeUpdate();
}
}catch (Exception e){
System.out.println("add one record to selectCoursee error:"+e);
}
}
public void deleteRecord(SelectCourse sc){
try{
if(cn!= null){
String qurey = "delete from selectCourse where Sno=?";
prepStmt = cn.prepareStatement(qurey);
prepStmt.setInt(1 , sc.getStudentNo());
prepStmt.executeUpdate();
}
}catch (Exception e){
System.out.println("delete one record from selectCourse error:"+e);
}
} public void updateRecord(SelectCourse sc){
try{
if(cn!=null){
String qurey = "update selectCourse Cno=?,Grade=? where Sno=?";
prepStmt = cn.prepareStatement(qurey);
prepStmt.setInt(1 , sc.getCourseNo());
prepStmt.setInt(2 , sc.getGrade());
prepStmt.setInt(3 , sc.getStudentNo());
prepStmt.executeUpdate();
}
}catch(Exception e){
System.out.println("update record form selectCourse error: "+e);
}
}
public ArrayList <SelectCourse> queryRecord(){
ArrayList <SelectCourse> scs = new ArrayList<SelectCourse>();
SelectCourse sc;
try {
if(cn!=null){
stmt = cn.createStatement();
ResultSet rs= stmt.executeQuery("SELECT * FROM selectCourse");
while(rs.next()){
sc = new SelectCourse();
sc.setStudentNo(rs.getInt("Sno"));
sc.setCourseNo(rs.getInt("Cno"));
sc.setGrade(rs.getInt("Grade"));
scs.add(sc);
}
}
}catch(Exception e){
System.out.println("query selectCourse error: "+e);
}
return scs;
}
public void closeConnection(){
try{
stmt.close();
prepStmt.close();
cn.close();
}catch (Exception e){
System.out.println("close connection of selectCourse error:"+e);
}
}
}

代码6:scTableCreator.java

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement; public class scTableCreator {
private Connection cn;
private Statement stmt;
private PreparedStatement prepStmt; public scTableCreator(){
cn = new DatabaseManager().openConnection();
} public void dropTalbe(){
try{
if(cn!=null){;
stmt = cn.createStatement();
stmt.execute("drop table selectCourse");
System.out.println("drop table selectCourse!");
}
}catch (Exception e){
System.out.println("drop table selectCourse error:"+e);
}
}
public void createTable(){
try{
if(cn!=null){
stmt = cn.createStatement();
stmt.execute("create table selectCourse(Sno int ,Cno int ,Grade int,foreign key(Sno) references Student(Sno),foreign key(Cno) references Course(Cno))");
System.out.println("create table selectCourse");
}
}catch (Exception e){
System.out.println("create table selectCourse error:"+e);
}
} public void insertInitRecords() {
try {
if (cn != null) {
String query = "insert into selectCourse(Sno ,Cno ,Grade ) values(? ,? ,?)";
prepStmt = cn.prepareStatement(query);
prepStmt.setInt(1, 20092725);
prepStmt.setInt(2, 1001);
prepStmt.setInt(3, 90);
prepStmt.executeUpdate(); prepStmt.setInt(1, 20092725);
prepStmt.setInt(2, 1002);
prepStmt.setInt(3, 96);
prepStmt.executeUpdate(); prepStmt.setInt(1, 20092740);
prepStmt.setInt(2, 1004);
prepStmt.setInt(3, 100);
prepStmt.executeUpdate(); System.out.println("some records added to selectCourse"); }
} catch (Exception e) {
System.out
.println("inset inital records to table selectCourse error:"
+ e);
}
}
public void closeConneciton(){
try{
stmt.close();
prepStmt.close();
cn.close();
} catch (Exception e){
System.out.println("close connection of selectCourse error:"+e);
}
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
scTableCreator creator = new scTableCreator();
creator.dropTalbe();
creator.createTable();
creator.insertInitRecords();
creator.closeConneciton();
} }

代码7:Student.java

public class Student {
//fileds of student
private int Sno;
private String Sname;
private String Ssex;
private int Sage;
private String Sdept; //Methods of student
public int getNo(){
return Sno;
}
public String getName(){
return Sname;
}
public String getSex(){
return Ssex;
}
public int getAge(){
return Sage;
}
public String getDept(){
return Sdept;
}
public void setNo(int Sno){
this.Sno = Sno;
} public void setName(String Sname){
this.Sname = Sname;
}
public void setSex(String Ssex){
this.Ssex = Ssex;
}
public void setAge(int Sage){
this.Sage = Sage;
}
public void setDept(String Sdept){
this.Sdept = Sdept;
}
public String toString(){
return Sno+" "+Sname+" "+Ssex+" "+Sage+" "+Sdept;
}
}

代码8:StudentManager.java

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.util.ArrayList; public class StudentManager {
private Connection cn;
private Statement stmt;
private PreparedStatement prepStmt; public StudentManager(){
cn = new DatabaseManager().openConnection();
} public void addStudent(Student student){
try{
if(cn!=null){
String query = "insert into student(Sno ,Sname ,Ssex ,Sage ,Sdept) values(? ,? ,? ,? ,? )";
prepStmt = cn.prepareStatement(query); //create a statement here
prepStmt.setInt(1 ,student.getNo());
prepStmt.setString(2 ,student.getName());
prepStmt.setString(3 ,student.getSex());
prepStmt.setInt(4 ,student.getAge());
prepStmt.setString(5 ,student.getDept());
prepStmt.executeUpdate();
}
} catch (Exception e){
System.out.println("add one student error!");
e.printStackTrace();
} } public void deleteStudent(Student student){
try{
if(cn!=null){
String query = "delete from student where Sno = ?";
prepStmt = cn.prepareStatement(query);
prepStmt.setInt(1 ,student.getNo());
prepStmt.executeUpdate();
}
}catch (Exception e){
System.out.print("delete student error"+e);
}
} public void updateStudent(Student student){
try{
if(cn!= null){
String query = "update student set Sname=?, Ssex=? ,Ssex=?,Sdept = ?"+"where Sno=?";
prepStmt = cn.prepareStatement(query);
prepStmt.setString(1 ,student.getName());
prepStmt.setString(2 ,student.getSex());
prepStmt.setInt(3 ,student.getAge());
prepStmt.setString(4 ,student.getDept());
prepStmt.setInt(5 ,student.getNo());
prepStmt.executeUpdate();
}
} catch (Exception e){
System.out.println("update student error:"+e);
}
} public ArrayList<Student> queryStudent(){
ArrayList<Student> students = new ArrayList<Student>();
Student student; try{
if(cn!=null){
stmt = cn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student") ;
while(rs.next()){
student = new Student();
student.setNo(rs.getInt("Sno"));
student.setName(rs.getString("Sname"));
student.setSex(rs.getString("Ssex"));
student.setAge(rs.getInt("Sage"));
student.setDept(rs.getString("Sdept"));
students.add(student);
}
}
}catch (Exception e){
System.out.println("query student error:"+e);
}
return students;
} public void closeConnection(){
try{
prepStmt.close();
stmt.close();
cn.close();
} catch (Exception e) {
System.out.println("close connection error:"+e);
}
}
}

代码9:StudentTableCreator.java

import java.util.ArrayList;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement; public class StudentTableCreator {
private Connection cn;
private Statement stmt;
private PreparedStatement prepStmt; public StudentTableCreator(){
cn = new DatabaseManager().openConnection();
} public void dropTable(){
try{
if(cn!=null){
stmt = cn.createStatement();
stmt.execute("drop table student");
System.out.println("drop table student");
}
}catch (Exception e){
System.out.println("drop table student error:"+e);
}
}
public void createTable(){
try{
if(cn!=null){
stmt = cn.createStatement();
stmt.execute("create table student(Sno int PRIMARY KEY,Sname varchar(18),Ssex varchar(4),Sage tinyint,Sdept varchar(20))");
System.out.println("table student created!");
}
}catch (Exception e){
System.out.println("create table student error:"+e);
}
} public void inserInitRecords(){
try{
if(cn!=null){
String query = "insert into student(Sno,Sname,Ssex,Sage,Sdept) values(?,?,?,?,?)";
prepStmt = cn.prepareStatement(query);
prepStmt.setInt(1 ,20092725);
prepStmt.setString(2 ,"张三");
prepStmt.setString(3 ,"男");
prepStmt.setInt(4 , 22);
prepStmt.setString(5 ,"信息学院");
prepStmt.executeUpdate(); prepStmt.setInt(1 ,20092740);
prepStmt.setString(2 ,"李四");
prepStmt.setString(3 ,"男");
prepStmt.setInt(4 ,23);
prepStmt.setString(5 ,"信息学院");
prepStmt.executeUpdate(); prepStmt.setInt(1 ,20092899);
prepStmt.setString(2 ,"王五");
prepStmt.setString(3, "男");
prepStmt.setInt(4 , 22);
prepStmt.setString(5 ,"材冶学院");
prepStmt.executeUpdate(); prepStmt.setInt(1 ,20093506);
prepStmt.setString(2 ,"赵六");
prepStmt.setString(3, "女");
prepStmt.setInt(4 ,21);
prepStmt.setString(5 , "工管学院");
prepStmt.executeUpdate(); prepStmt.setInt(1 , 20101105);
prepStmt.setString(2 , "刘七");
prepStmt.setString(3 , "男");
prepStmt.setInt(4 ,20);
prepStmt.setString(5 ,"软件学院");
prepStmt.executeUpdate(); System.out.println("Insert 5 records");
}
}catch (Exception e){
System.out.println("insert records error :"+e);
}
}
public void closeConnection(){
try{
prepStmt.close();
stmt.close();
cn.close();
System.out.println("student table creator connection !");
}catch (Exception e){
System.out.println(" student table close connection error:"+e);
}
}
public static void main(String[] args){
ArrayList<Student> s = new ArrayList<Student>();
StudentTableCreator creator = new StudentTableCreator();
creator.dropTable();
creator.createTable();
creator.inserInitRecords();
StudentManager sm = new StudentManager();
s = sm.queryStudent();
System.out.print(s);
creator.closeConnection();
}
}

数据库使用:mysql,驱动使用
运行结果:

Java实验2-数据库编程的更多相关文章

  1. 20165324 Java实验五 网络编程与安全

    20165324 Java实验五 网络编程与安全 一.实验报告封面 课程:Java程序设计 班级:1653班 姓名:何春江 学号:20165324 指导教师:娄嘉鹏 实验日期:2018年5月28日 实 ...

  2. 2018-2019-2-20175323 java实验五 网络编程与安全

    20175323 java实验五 网络编程与安全 任务一 ①编写MyBC.java实现中缀表达式转后缀表达式的功能 ②编写MyDC.java实现从上面功能中获取的表达式中实现后缀表达式求值的功能 基本 ...

  3. Java实验五网络编程与安全

    实验五 网络编程与安全 实验准备 博客 活动一 两人一组结对编程: 0. 参考http://www.cnblogs.com/rocedu/p/6766748.html#SECDSA 1. 结对实现中缀 ...

  4. Java实验项目三——编程实现Person类,学生类的设计及其继承关系

    Program: 编程实现Person类,学生类的设计及其继承关系 代码如下: 定义抽象类Person 1 /* 2 * Description:建立抽象类 3 * 4 * Written By:Ca ...

  5. java实验7-多线程编程

    1 利用Thread和Runnable创建线程 [实验目的] (1)理解用实现Runnable接口的方法实现多线程. (2)掌握线程优先级的设置. (3)加深对线程状态转换的理解. [实验要求] 要求 ...

  6. Java与mysql数据库编程中遇见“Before start of result set at com.mysql.jdbc.SQLError.createSQLException” 的解决办法

    这个Bug是因为在取出ResultSet对象,对其进行操作时,没有采用.next()方法将ResultSet对象的光标移至指定行,不管Statement对象执行SQL语句是否十分确定能搜出记录,也不可 ...

  7. Java实验五

    20145113 Java实验五 网络编程及安全 实验内容 对于客户端与服务器端:修改原代码,使其可以实现连续的传消息,并且传送文件. 对于加解密部分: 对于原先的加密只加密"hello w ...

  8. Java JDBC数据库编程

    课程  Java面向对象程序设计 一.实验目的 掌握数据库编程技术 二.实验环境 1.微型计算机一台 2.WINDOWS操作系统,Java SDK,Eclipse开发环境,Microsoft SQL  ...

  9. Java实验报告五:Java网络编程及安全

    Java实验报告五:Java网络编程及安全                                                                               ...

随机推荐

  1. 安装Mysql提示1045错误解决方法

    MySQL安装提示一下错误 The security settings could not be applied to the database because the connection has ...

  2. Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'xxx': no matching editors or conversion strategy found

    今天在完成项目的时候遇到了下面的异常信息: 04-Aug-2014 15:49:27.894 SEVERE [http-apr-8080-exec-5] org.apache.catalina.cor ...

  3. 加州大学伯克利分校Stat2.2x Probability 概率初步学习笔记: Midterm

    Stat2.2x Probability(概率)课程由加州大学伯克利分校(University of California, Berkeley)于2014年在edX平台讲授. PDF笔记下载(Acad ...

  4. 数据结构2 静态区间第K大/第K小

    给定数组$A[1...N]$, 区间$[L,R]$中第$K$大/小的数的指将$A[L...R]$中的数从大到小/从小到大排序后的第$K$个. "静态"指的是不带修改. 这个问题有多 ...

  5. Beta版本——第五次冲刺博客

    我说的都队 031402304 陈燊 031402342 许玲玲 031402337 胡心颖 03140241 王婷婷 031402203 陈齐民 031402209 黄伟炜 031402233 郑扬 ...

  6. range和xrange梳理

    一.python2.7 range 用户获取指定范围内的数,range([start,] stop[, step]) >>> range(1,5) #代表从1到5(不包含5) [1, ...

  7. MySQL好用的数学函数

    最近项目很忙,分给我的功能都比较复杂,还好能应付的下来.在工作的过程中,我发现使用mysql的自带函数能够极大的减少程序的复杂度.这是必然的,使用mysql的函数,能够在程序里面省却很多的循环遍历.但 ...

  8. oneM2M

    http://www.ccsa.org.cn/organization/intro.php?org=oneM2M 一.成立背景 随着物联网技术研发及市场推广的不断深入,全球各通信标准化组织都在加强物联 ...

  9. css009 装饰网站的导航

    css009 装饰网站的导航 1.         选择定义样式的链接 1.连接的状态: A.未访问  a:link{C;} B.已访问  a:visited{ color : red; } C.鼠标 ...

  10. c#优化

    优化反射 http://kb.cnblogs.com/page/172119/ http://www.2cto.com/kf/201301/182765.html http://blog.sina.c ...