使用eclipse连接oracle12c数据库,并完成了一些简单的操作(HashMap的使用)
任务:计算每位老师的工作量(Java编程)
计算方法是:讲授的每门课程的学时数*该门课程选修的学生人数,然后求和;
首先需要导入一个包,参考了以下这个博客
https://blog.youkuaiyun.com/hyh17808770899/article/details/106872076
以下是三个表,分别为课程表,课程安排表和学生选课表,



import java.sql.*;
import java.util.HashMap;
import java.util.Iterator;
import com.sun.javafx.collections.MappingChange.Map;
public class test {
public static void main(String args[]) throws ClassNotFoundException, SQLException {
//1.加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//2.获取连接对象
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String user = "***"; // 此处为自己的oracle用户名
String password="123456"; // 这里为用户名所对应的密码
Connection connection = DriverManager.getConnection(url,user,password);
if(connection==null) {
System.out.println("oracle失败");
}else {
System.out.println("oracle连接成功");
}
/*String sql = "select sno,sum(grade) sg from sc group by sno";
try{
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
String sno =resultSet.getString("sno");
double sg = resultSet.getDouble("sg");
System.out.println(sno);
System.out.println(sg);
}
}catch(SQLException e){
e.printStackTrace();
}*/
// 统计出选修了每一门课程的 学生数*每一门的课时数,并将其存储在map_1中
String sql_1 = "select cno, count(*) num from sc group by cno";
String sql_2 = "select cno, class_hour from course";
HashMap<String, Double> map_1 = new HashMap<String, Double>();
try{
Statement statement_1 = connection.createStatement();
ResultSet resultSet_1 = statement_1.executeQuery(sql_1);
while (resultSet_1.next()){
String cno_1 = resultSet_1.getString("cno");
double num = resultSet_1.getDouble("num");
Statement statement_2 = connection.createStatement();
ResultSet resultSet_2 = statement_2.executeQuery(sql_2);
while(resultSet_2.next()){
double workload;
String cno_2 = resultSet_2.getString("cno");
double class_hour = resultSet_2.getDouble("class_hour");
if(cno_1.equals(cno_2)){
workload = num*class_hour;
map_1.put(cno_2, workload);
System.out.println("课程号为"+cno_2+"的总学时为:"+workload);
break;
}
}
}
}
catch(SQLException e){
e.printStackTrace();
}
// 统计每一个教师的工作量,并将其存入map_2
String sql_3 = "select tno, cno from tc";
Statement statement_3 = connection.createStatement();
ResultSet resultSet_3 = statement_3.executeQuery(sql_3);
HashMap<String, Double> map_2 = new HashMap<String, Double>();
while(resultSet_3.next()){
String tno = resultSet_3.getString("tno");
String cno = resultSet_3.getString("cno");
double class_hours = map_1.get(cno);
if(!map_2.containsKey(tno))
map_2.put(tno, class_hours);
else
map_2.put(tno, map_2.get(tno)+class_hours);
}
// 遍历整个map_2将教师的工作量输出出来
for(HashMap.Entry<String, Double> entry : map_2.entrySet()){
String mapKey = entry.getKey();
double mapValue = entry.getValue();
System.out.println("工号为"+mapKey+"的教师的工作量为:"+mapValue+"学时");
}
}
}
结果:

Eclipse连接Oracle12c
1997

被折叠的 条评论
为什么被折叠?



