我有一个包含6列的表:用户标识,名字,姓氏,标题,班组和电子邮件。当我只想更新其中的一个时,我只会将文本输入到相应的文本字段中。例如,如果我想更新名字,我只会写新的名字,我不会把任何名字,标题等。当我用SQL进行更新时,如果一个字段为空,它将数据库中的值更改为空
问题是,当我没有为这些其他文本字段,数据库假定我想将这些值更新为空,并且当我运行数据库时,这里什么都没有了。我该如何解决?
String ID = textID.getText();
String first = textFirstName.getText();
String last = textLastName.getText();
String title = textTitle.getText();
String squad = textSquad.getText();
String email = textEmail.getText();
int newID = Integer.parseInt(ID);
int newSquad = Integer.parseInt(squad);
try {
if(first != null) {
String sql = "Update colleagues " + "set firstname = ? " + "where userid = ?";
PreparedStatement upd = myConn.prepareStatement(sql);
upd.setString(1, first); // replace first ? with value for first name
upd.setInt(2, newID); // replace second ? with value for userid
upd.executeUpdate();
}
if(last != null) {
String sql = "Update colleagues " + "set lastname = ? " + "where userid = ?";
PreparedStatement upd = myConn.prepareStatement(sql);
upd.setString(1, last);
upd.setInt(2, newID);
upd.executeUpdate();
}
// ...
@joanolo我已经决定使用'first.length()> 0',但是我得到这个错误:线程“AWT-EventQueue-0”中的异常java.lang.NumberFormatException:对于输入字符串:“” – Zelda
我想这发生在别的地方......预计你会传递一个空字符串。浏览你的代码并找出答案。 – joanolo
@joanolo它现在有效!我似乎无法找到表示此问题已得到解答的复选标记。我看到的只是一颗星 – Zelda