我正嘗試使用Java JDBC更新我的表。但我不知道如何使用準備好的語句來調用我的主鍵。我嘗試爲我的數據庫的列創建一個USER_ID
對象,但不知道從何處開始。我將如何確定我是否已經更新了我的數據庫?如何獲得執行select語句的主鍵
INSERT
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);
}
}
}
在這裏,如果我插入一個新值,它會載入新值的數據庫。
SELECT
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?
張貼您的擺動部件定義 – Musaddique
已編輯擺動部件。謝謝。請再次檢查我的帖子。 – Francisunoxx