gpt4 book ai didi

java - 为什么我的sql代码在结果集中无法正常运行

转载 作者:行者123 更新时间:2023-12-02 05:49:53 25 4
gpt4 key购买 nike

我正在为我的minecraft服务器编写一个bukkit插件,我的代码要么在我编写类和方法的方式上有错误,要么如我推测的在结果集部分有错误。

它没有检测到我的播放器已经在 SQL 表中。这是在 hasPlayer 方法中。

@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player p = event.getPlayer();
SQLCheckPlayer pCheck = new SQLCheckPlayer();
pCheck.p = p;
boolean i = pCheck.hasPlayer();
if (i == false) {
boolean n = pCheck.addPlayer();
if (n == true) {
p.sendMessage("You have been added to our database");
} else {
p.sendMessage("There was errors in trying to add you to our database");
}
} else {
p.sendMessage("You are in our database");
}


}

SQLCheckPlayer 类

public class SQLCheckPlayer {

Player p;

public boolean hasPlayer() {
UUID pUUID = p.getUniqueId();
String query = "SELECT playerID FROM playerInfo;";
try {
if (sqlConnection.getDatabaseConnection() != null) {
Statement st = sqlConnection.getDatabaseConnection().createStatement();
ResultSet rs = st.executeQuery(query);
if (rs != null) {
do{
if(pUUID.toString() == rs.toString()) {
st.close();
Bukkit.broadcastMessage("Player successfully added");
return true;
}
} while(rs.next());

}
st.close();
} else {

Bukkit.broadcastMessage("Database connection is null");
return false;
}

return false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Bukkit.broadcastMessage("Sql Exception");
return false;
}
}

public boolean addPlayer() {
UUID pUUID = p.getUniqueId();

try {
PreparedStatement st = sqlConnection.getDatabaseConnection().prepareStatement("INSERT INTO playerInfo (playerID, playerName, playerDiamonds) VALUES (?, ?, ?)");
st.setString(1, pUUID.toString());
st.setString(2, p.getDisplayName());
st.setInt(3, 0);
st.executeUpdate();
st.close();
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}

}
}

在我被添加到数据库后(它可以成功完成),每当我重新加入时,它应该说“您在我们的数据库中”,但它总是显示“尝试将您添加到我们的数据库中时出错” 。在打印堆栈跟踪时,它说代码试图再次将我添加到数据库中,但它不能,因为我在playerUUID列上放置了一个唯一的选项卡。

最佳答案

你告诉我们的是

boolean i = pCheck.hasPlayer();
if (i == false) {
boolean n = pCheck.addPlayer();
if (n == true) {
p.sendMessage("You have been added to our database");
} else {
p.sendMessage("There was errors in trying to add you to our database");
}
} else {
p.sendMessage("You are in our database");
}

输出“尝试将您添加到我们的数据库时出错”

这是因为 pCheck.hasPlayer() 将为 false 由于

UUID pUUID = p.getUniqueId();
String query = "SELECT playerID FROM playerInfo;";

不考虑pUUID。相反,它会查找将 "playerId" 作为其 UUID 的条目。结果是尝试再次插入该播放器,由于某些数据库约束(唯一主键或类似的东西),这将不起作用。

您可能想将查询重写为类似的内容

String query = "SELECT " + pUUID + " FROM playerInfo;";

然后重试。我希望这会有所帮助...

关于java - 为什么我的sql代码在结果集中无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56059822/

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