【问题标题】:DIsplay rows in a table by substituting value for a given column通过替换给定列的值来显示表中的行
【发布时间】:2016-04-01 09:35:37
【问题描述】:

我有两个表部门和员工都有共同的列department_id

首先我显示了部门表中的部门名称,第二个雇员表中的employee_id。现在我的查询是我想从用户那里获取部门名称并与部门表进行比较,如果名称可用,结果应该显示该特定部门的员工 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);

     }
   }
}

【问题讨论】:

  • 导入 java.sql.*; class OracleCon { public static void main(String args[]) { try { //step1 加载驱动类 Class.forName("oracle.jdbc.driver.OracleDriver"); //step2 创建连接对象 Connection con= DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","hr"); //step3 创建语句对象 Statement stmt = con.createStatement(); ResultSet rs=stmt.executeQuery("从部门中选择 *"); while(rs.next()) { String dname=rs.getString("DEPARTMENT_NAME"); System.out.println(dname); }
  • 语句 stmt1=con.createStatement(); ResultSet rs1=stmt1.executeQuery("select * from employees");而(rs1.next()){整数eno=rs1.getInt(“employee_id”); System.out.println(eno); } con.close(); } 捕捉(异常 e) { System.out.println(e); } } }
  • 您作为 cmets 发布的 sn-ps 完全不可读(也许 Jon Skeet 能够阅读此内容,但这里的大多数用户不能)。编辑您的问题以将它们添加到问题正文中,格式正确。
  • 为什么不在使用 Join 的单个 SQL 请求中执行此操作?

标签: java jdbc


【解决方案1】:

我将假设您的员工和部门表具有外键关系(或逻辑键关系),即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();
.....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2022-10-02
    • 1970-01-01
    相关资源
    最近更新 更多