从PostgreSQL数据库中获取数据

时间:2014-09-09 09:26:34

标签: sql postgresql

我在名为doctordepartment的PostgreSQL数据库中创建了两个表。我在dept_id表中使用doctor作为外键。现在我已经在Eclipse中列出了部门,但是当我点击某个部门时,应该列出特定表中的医生。所以我请求您提供从doctor_list表中获取doctor的代码。有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

创建表格

create table Department (
dept_id serial primary key, 
dept_name text);

create table Doctor (
id serial primary key, 
name text not null, 
dept_id integer references Department (dept_id)
);

添加数据

insert into department(dept_name) values('Main dept');
insert into department(dept_name) values('Another dept');
insert into doctor(name, dept_id) values('Adam', 1);
insert into doctor(name, dept_id) values('Eva', 2);

获取特定部门医生名单的简单查询。

select * from doctor where dept_id = 1;

答案 1 :(得分:0)

假设您使用Java(如果没有,然后忽略此答案),并且您正在制作简单的Java应用程序(而不是Java EE),则必须首先建立与数据库的连接。 This tutorial会告诉您如何操作。然后你必须使用它。 Here解释了如何执行此操作(再次建立连接)。

从第二个链接中修改代码可能看起来像:

private void LoadDoctors(Connection conn, LinkedList listOfBlogs)
  {
    try 
    {
      Statement st = conn.createStatement();
      ResultSet rs = st.executeQuery("SELECT d.id as \"did\",d.name as \"dnme\",dd.id as \"ddid\",dd.name as \"ddname\" FROM doctors d JOIN departments dd ON dd.id=d.dept_id ORDER BY id");
      while ( rs.next() )
      {
        Doctor doc= new Doctor ();
        doc.id        = rs.getInt("did");
        doc.name= rs.getString("dname");
        doc.department= new Department(rs.getInt("ddid"),rs.getInt("ddname"));
        list.add(doc);
      }
      rs.close();
      st.close();
    }
    catch (SQLException se) {
      System.err.println("Threw a SQLException creating the list of blogs.");
      System.err.println(se.getMessage());
    }
  }