我正在执行一种方法,该方法应该更新我在本地数据库中具有的标签(卡)的位置,此方法(UpdateWallet)接受用户的输入并根据用户插入的内容覆盖数据库中的记录。在此方法代码的末尾,如果在数据库中找到了输入的“标签”并成功更新了其位置,则它应返回true并输出一条消息,说明更新已成功。否则,返回false,但是我有2个问题:
1-虽然我收到上一条消息(它已成功更新),但值没有更新。
2-无论我输入什么值,我的方法都很满意,并声称它“更新”了记录。即使插入的标签在我的数据库中不存在!在这种情况下,它应该只返回false。
我的更新方法:
public boolean UpdateWallet(wallet upWallet) throws SQLException {
Connection dbConnection = null;
Statement statement = null;
String update = " UPDATE wallets SET Location = '"+upWallet.getWalletLocation()+"' WHERE Tag = '"
+ upWallet.getWalletTag()+"';";
try {
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
// execute SQL update
statement.executeUpdate(update);
System.out.println("It has been updated successfully");
} catch (SQLException e) {
System.out.println(e.getMessage());
return false;
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
return true;
}
控制器代码:
System.out.println("Please enter a tag to update its location");
String tag = input.next();
System.out.println("Please enter Location ");
String loc = input.next();
wallet w = new wallet(tag,loc);
WalletsDAO.UpdateWallet(w);
钱包类:
public class wallet {
private String Name;
private String Location;
private String Tag;
public wallet(String Name, String Location, String Tag) {
this.Name = Name;
this.Location = Location;
this.Tag = Tag;
}
public wallet(String Tag) {
this.Tag = Tag;
}
public wallet(String Location, String Tag) {
this.Name = Name;
this.Location = Location;
this.Tag = Tag;
}
public String getWalletName() {
return Name;
}
public void setWalletName(String Name) {
this.Name = Name;
}
public String getWalletLocation() {
return Location;
}
public void setWalletLocation(String Location) {
this.Location = Location;
}
public String getWalletTag() {
return Tag;
}
public void setWalletTag(String Tag) {
this.Tag = Tag;
}
@Override
public String toString() {
String p = (this.Name + ',' + this.Location + ',' + this.Tag);
return p;
}
}
有人可以帮我吗?
答案 0 :(得分:0)
您可以在javadoc中查看executeUpdate:https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)
您应该使用executeUpdate()的int结果,以了解是否未更新任何值或某个值,而不是异常(如果未更新任何值也不例外)
答案 1 :(得分:0)
问题在于以下调用:
wallet w = new wallet(tag,loc);
应该是
wallet w = new wallet(loc,tag);
匹配构造函数public wallet(String Location, String Tag)
。
另一方面,请从您的代码中删除/注释以下代码中的注释行(即this.Name = Name
):
public wallet(String Location, String Tag) {
//this.Name = Name;
this.Location = Location;
this.Tag = Tag;
}