如何获取主键来执行更新语句 [英] How to get the primary key to execute an update statement
问题描述
我正在尝试使用Java JDBC更新我的表。但我不知道如何使用Prepared Statement调用我的主键。我尝试为我的数据库列创建一个 USER_ID
对象,但不知道从哪里开始。我如何确定我是否已更新我的数据库?
I'm trying to update my table using Java JDBC. But I don't have any idea how can I call my Primary Key using Prepared Statement. I try to make an USER_ID
object for the column of my database but don't know where to start. How will I determine if I already updated my database?
代码
String updateEmployee = employeeTf.getText();
String updateDepartment = departmentTf.getText();
if(updateEmployee.isEmpty() && updateDepartment.isEmpty()){
JOptionPane.showMessageDialog(null, "You didn't update it");
}
else if(updateEmployee.isEmpty()){
JOptionPane.showMessageDialog(null, "Please update your name");
}
else if(updateDepartment.isEmpty()){
JOptionPane.showMessageDialog(null, "Please update your department");
}
else{
String updateQuery = "UPDATE SAMPLE SET EMPLOYEENAME = ?, DEPARTMENT = ? WHERE USER_ID = ?";
try(Connection con = DBUtilities.getConnection(DBType.JDBC);
PreparedStatement myPs = con.prepareStatement(updateQuery);){
myPs.setString(1, employeeTf.getText());
myPs.setString(2, departmentTf.getText());
myPs.setInt(3, "WHAT GOES HERE");
//Execute insert SQL Statement
myPs.executeUpdate();
System.out.print("Updated");
} catch (SQLException ex) {
DBUtilities.processException(ex);
}
}
推荐答案
如果您正在进行更新记录必须已存在于您的表中。
您的申请大致需要以下流程:
If you are doing an UPDATE the record must already exist in your table. Roughly your application needs the following process:
- 从数据库中读取记录
- 将记录中的数据放入GUI控件中,并将ID值保留在某处。
- 现在用户点击保存:您从GUI传输值控制你的PreparedStatement并使用步骤2中的ID来构建where参数。
- 提交。
- Read the record from the database
- Put data from the record into your GUI controls and also keep the ID value somewhere.
- Now the user hits "Save": You transfer the values from GUI controls into your PreparedStatement and use the ID from step 2 to build the where parameter.
- Commit.
如果要创建新记录,请跳过步骤1,因此没有ID值。
然后在第3步中执行UPDATE,而不需要执行更新。
If you want to create a new record, you skip step 1 and therefore have no ID value. Then instead of doing an UPDATE in step 3 you will need to do a INSERT.
这篇关于如何获取主键来执行更新语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!