选择名字和多重查询时仅插入ID

时间:2018-09-24 12:14:38

标签: java database

我正在尝试在选择Doctor的名称时插入Doctor的约会,它将仅在表数据库中插入ID,并将Doctor Availability更新为0 这是我的代码

try{
        String sql = "INSERT INTO Appointment_Table (Doc_ID, Department_ID, SchedDate, Patient_ID) VALUES\n" +
                     "( (SELECT ID from User_Table where First_Name = ?), (SELECT Department_ID from User_Table WHERE First_Name = ?), ?, (Select Patient_ID from Patient_Records where First_Name = ?));";
        pst = conn.prepareStatement(sql);
        rs = pst.executeQuery();
        pst.setString(1, (String) DoctorNames.getSelectedItem());
        pst.setString(2, (String) DoctorNames.getSelectedItem());
        String add1 = ((JTextField)jDateChooser1.getDateEditor().getUiComponent()).getText();
        String add2 = DoctorTime.getText();
        pst.setString(3, add1+"-/-"+add2+"-PM");
        pst.setString(4, (String) DoctorPatient.getSelectedItem());


        try{
            String sql1 = "Update User_Table set Availability = 0  where First_Name LIKE ?";
            pst = pst = conn.prepareStatement(sql1);
            rs = pst.executeQuery();
            pst.setString(1, (String) DoctorNames.getSelectedItem());
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, e);
            e.printStackTrace();
        }

    }catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
        e.printStackTrace();
    }finally {
        try {
            rs.close();
            pst.close();
        }catch(Exception e){

        }
    }

2 个答案:

答案 0 :(得分:0)

尝试在 SELECT 之后添加 LIMIT 0,1 ,如下所示:

INSERT INTO Appointment_Table (Doc_ID, Department_ID, SchedDate, Patient_ID) VALUES 
( (SELECT ID from User_Table where First_Name = ? LIMIT 0,1 ), (SELECT Department_ID from User_Table WHERE First_Name = ? LIMIT 0,1 ), ?, (Select Patient_ID from Patient_Records where First_Name = ? LIMIT 0,1 ));

它用于MySql DBMS for SQL Server使用前1个关键字

SELECT TOP 1 ID from User_Table where First_Name = ?

答案 1 :(得分:0)

在表格中添加3个组合框,其中一个用于Doc_ID,一个用于Department_ID,另一个用于Patient_ID

创建此类

class ComboItem
{
    private String key;
    private String value;

    public ComboItem(String key, String value)
    {
        this.key = key;
        this.value = value;
    }

    @Override
    public String toString()
    {
        return key;
    }

    public String getKey()
    {
        return key;
    }

    public String getValue()
    {
        return value;
    }
}

将ComboItem添加到您的comboBox。

comboBox.addItem(new ComboItem("doctor name ", "Doc_ID"));
comboBox.addItem(new ComboItem("doctor 2 name ", "Doc_ID 2"));
comboBox.addItem(new ComboItem("doctor 3 name ", "Doc_ID 3"));

每当您获得选定的项目。

Object item = comboBox.getSelectedItem();
String value = ((ComboItem)item).getValue();

编辑您的SQL

INSERT INTO Appointment_Table (Doc_ID, Department_ID, SchedDate, Patient_ID) VALUES (combo_Doc_ID_value,combo_Department_ID_value,?,combo_Patient_ID_value)