如何获取主键来执行select语句

时间:2016-03-03 07:10:34

标签: java mysql swing jdbc

我正在尝试使用Java JDBC更新我的表。但我不知道如何使用预备声明调用我的主键。我尝试为我的数据库列创建一个USER_ID对象,但不知道从哪里开始。我如何确定我是否已更新我的数据库?

插入

   private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {
   String inputEmployee = employeeTf.getText();
   String inputDepartment = departmentTf.getText();

   if(inputEmployee.isEmpty() && inputDepartment.isEmpty()){
         JOptionPane.showMessageDialog(null, "Please fill up!");
    }
    else if(inputEmployee.isEmpty()){
        JOptionPane.showMessageDialog(null, "Please enter your username");
    }
    else if(inputDepartment.isEmpty()){
        JOptionPane.showMessageDialog(null, "Please enter your password");
    }
    else{
        String myQuery = "INSERT INTO SAMPLE (EMPLOYEENAME,DEPARTMENT) VALUES (?,?)";

        try(Connection con = DBUtilities.getConnection(DBType.JDBC);
        PreparedStatement myPs = con.prepareStatement(myQuery);
            ){

            myPs.setString(1, employeeTf.getText());
            myPs.setString(2, departmentTf.getText());

            myPs.executeUpdate();

            System.out.print("Record is inserted");


        } catch (SQLException ex) {
            DBUtilities.processException(ex);
       }
    }
   }

如果我插入一个新值,它会将新值加载到数据库。

选择

private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {
String searchEmployee = searchName.getText(); //SWING COMPONENTS
String searchDept = searchDepartment.getText();//SWING COMPONENTS

    String selectQuery = "SELECT EMPLOYEENAME,DEPARTMENT FROM SAMPLE WHERE USER_ID = ?";

    try {
        Connection con = DBUtilities.getConnection(DBType.JDBC);
        PreparedStatement myPs = con.prepareStatement(selectQuery,ResultSet.CONCUR_UPDATABLE,ResultSet.TYPE_SCROLL_INSENSITIVE);

        ResultSet myRs = myPs.executeQuery();

        while(myRs.next()){
           String name = myRs.getString(1);
           String department = myRs.getString(2);
        }

    } catch (SQLException ex) {
        DBUtilities.processException(ex);
    }
  }

SCREENSHOT

Screenshot

填写 searchName和searchDepartment文本字段的字段后。正如你在这里看到的,我在这里点击了#34;搜索"按钮。 我希望 searchName和searchDepartment 的值将打印到 employeeTf和departmentTf 的文本字段中 我如何在这里使用setText?

1 个答案:

答案 0 :(得分:1)

 while(myRs.next()){
    String name = myRs.getString(1);
    String department = myRs.getString(2);
    nameText.setText(name);
    deptText.setText(department);
 }

我认为nameTextdeptText是swing文本组件的对象

如果这里无法访问它们,那么你可以创建所有字段的对象并从结果集中放入数据并返回该对象并在那里使用。