从Java将数据插入SQL Server的外键表中

时间:2019-05-19 17:49:53

标签: java sql-server database netbeans-8

我在SQL SERVER中有3个表:表Employee,表HourlyEmployee和表SalariedEmployee。在Netbeans上的JFrame中,我有2个单选按钮,用户可以按小时或按小时选择。如果选择了每小时单选按钮,则会在下面启用一个文本字段框。现在,我希望用户可以在该框中输入小时费率,例如4.5 ..,并且希望将4.5保存在表HourlyEmployee中。到目前为止,我已经在Submit上编写了此代码,但是无法正常工作:(最重要的是在哪里有if(rHourly.isSelected())...)

try{
            conn = DriverManager.getConnection(connectionUrl);
            String query ="insert into Employee "
            + "(Name,Surname,Gender,DOB,"
            + "Status,Address,Email,"
            + "Mobile, DateHired, Salary, Job, Type, Image) values 
(?,?,?,?,?,?,?,?,?,?,?,?,?)";
            pst = conn.prepareStatement(query);

            pst.setString(1, txtName.getText());
            pst.setString(2, txtSurname.getText());               
            if(rMale.isSelected()) {
                gender="Male";
            }
            if(rFemale.isSelected()) {
                gender="Female";
            }
            pst.setString(3,gender);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String addDate = df.format(dpDOB.getDate());
            pst.setString(4,addDate);
            pst.setString(5,cbStatus.getSelectedItem().toString());
            pst.setString(6,txtAddress.getText());
            pst.setString(7,txtEmail.getText());
            pst.setString(8,txtContact.getText());
            String addDate2 = df.format(dpHired.getDate());
            pst.setString(9,addDate2);
            pst.setString(10,txtSalary.getText());
            pst.setString(11,txtJob.getText());
            if(rHourly.isSelected()) {
                type="Hourly";
                String sql = "insert into HourlyEmployee (HourlyRate, 
EmployeeID, Name, Surname) values (?,?,?,?)";
                pst = conn.prepareStatement(sql);
                pst.setString(1, txtHourly.getText());
                pst.execute();
            }
            if(rSalaried.isSelected()) {
                type="Salaried";
                String sql1 = "insert into SalariedEmployee (Salary, 
EmployeeID, Name, Surname) values (?,?,?,?)";
                pst = conn.prepareStatement(sql1);
                pst.setString(2, txtSalaried.getText());
            }
            pst.setString(12,type);
            pst.setBytes(13,personImg);

            pst.executeUpdate();
            JOptionPane.showMessageDialog(null,"Data is saved 
successfully");


        }catch(Exception e) {
            JOptionPane.showMessageDialog(null,e);
        }
    }

任何帮助将不胜感激! :D

0 个答案:

没有答案