我有两个表部门,员工都有共同的栏目部门_id
首先,我从employees表第二个employee_id中显示了来自employees表的部门名称。现在我的查询是我想从用户获取部门名称并与部门表进行比较,如果名称可用,结果应显示该特定部门的员工ID
import java.sql.*;
class OracleCon {
public static void main(String args[]) {
try {
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con= DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","hr","hr");
//step3 create the statement object
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from departments");
while (rs.next()) {
String dname = rs.getString("DEPARTMENT_NAME");
System.out.println(dname);
}
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select * from employees");
while (rs1.next()) {
Integer eno = rs1.getInt("employee_id");
System.out.println(eno);
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
答案 0 :(得分:0)
我将假设您的员工和部门表具有外键关系(或逻辑密钥关系),例如employees.department_name = department.department_name。一个简单的数据库连接应该完成工作。
此外,如果您想按部门名称(或任何其他变量)进行搜索,请使用PreparedStatement,而不是Statement。
String sql = "select e.* from employee e, department d where d.department_name = ? and d.department_name=e.deparment.name"); )// ? will be replaced by a parameter obtained from a user
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, deptName); //deptName is obtained from the user
ResultSet rs = stmt.executeQuery();
.....