gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:41:08 25 4
gpt4 key购买 nike

我正在尝试使用 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

填写searchName 和searchDepartment 文本字段的字段后。正如您在这里看到的,我点击了“搜索”按钮。我希望 searchName 和 searchDepartment 的值将打印到 employeeTf 和 DepartmentTf 的文本字段我将如何在这里使用 setText?

最佳答案

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

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

如果这些在此处无法访问..那么您可以创建所有字段的对象并从结果集中放入数据并返回该对象并在此处使用。

关于java - 如何获取主键来执行select语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35765398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com