我怎样才能有一个 SQL 语句在单击按钮时更新数据,而不是在页面加载时执行?
我有一个非常简单的表格,其中包含球员姓名、球员得分和球员 ID 属性,并且只有一行。当我在此页面上时,我希望按钮执行更新查询以增加玩家得分,但每次页面加载时都会发生这种情况。
是否有一个布尔值或我可以设置的东西来防止它在每次加载时将玩家分数加 1?
请不要问我为什么在这种情况下使用 JSP。这样做不好,我知道,但这是我的要求。
这是我的代码:
<%@ page contentType="text/html" %>
<%@ page import="java.text.DecimalFormat" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.lang*" %>
<!DOCTYPE html>
<html>
<head>
<title>Player scores</title>
<script>
function reloadPage() {
location.reload();
}
</script>
</head>
<body>
<%!
String name = "";
Integer score = 0;
Integer pID = 0;
%>
<form name="form1" method="POST" onsubmit="return false">
<p align="center">
<input type="BUTTON" value="+" onclick="reloadPage();"/>
</p>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");
Statement stmnt = conn.createStatement();
stmnt.executeUpdate("update players set playerScore=playerScore+1 where playerID=1");
} catch (Exception e) {
}
%>
</form>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");
Statement stmnt = conn.createStatement();
ResultSet rs = stmnt.executeQuery("select playerID, playerName, playerScore from players where playerID=1");
if (rs.next()) {
name = rs.getString("playerName");
score = rs.getInt("playerScore");
pID = rs.getInt("playerID");
} else {
name = "-";
score = 0;
pID = 404;
}
} catch(Exception e) {
}
%>
<table align="center">
<tr>
<th>Player name:</th>
<td id="pID"><%=name%></td>
</tr>
<tr>
<th>Player score:</th>
<td id="pN"><%=score%></td>
</tr>
<tr>
<th>Player id:</th>
<td id="pi"><%=pID%></td>
</tr>
<p class="center">
<a href="Page2.jsp">Go back</a>
</p>
</table>
</body>
</html>