【发布时间】:2018-12-22 03:04:01
【问题描述】:
-------- 2 天前 --------
“我只为网站的“喜欢”做了一个数据库。数据库有一个表(喜欢),里面有几个字段(Like1,Like2,等等......)
在一个 JSP 文件中,我建立了连接并显示了一个字段的值(Like1)。
但我想做的是:通过点击某个文本,值加一,将数据库中的值从 Like1 更新为 Like1 + 1。”
--- 编辑 ---
当我点击按钮时,给我看这个:
当我刷新时,数据不会改变。所以我认为如果我没有显示错误,它会起作用。
我想要的是,当你按下按钮时,数据库数据增加 1。
结构:
index.jsp:
<body>
<div class="col-lg-12">
<form method="post" action="likeCount">
<button type="submit" name="click"><b style="color:#ff5858;font-size: 24px;">❤</b></button>
<% try {
Connection conn = DBConnect.connect();
PreparedStatement pstmt = conn.prepareStatement("SELECT Like1 from Likes");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {%>
<input type="text" hidden name="counts" value="<%=rs.getInt("Like1")%>" />
</form>
<span style="font-weight: bold"><%=session.getAttribute("count")==null)?rs.getInt("Like1"):(session.getAttribute("count"))%></span><% }
} catch (SQLException ex) {
System.out.println("Error in select: " + ex.getMessage());
}%>
</div>
</body>
DBConnect.java:
package myPack;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnect {
public static Connection connect() throws SQLException {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/Likes";
String username = "root";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Error : " + e.getMessage());
}
return conn;
}
}
likeCount.java:
package myPack;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class likeCount {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
/*check whether the button is clicked*/
if (request.getParameter("click") != null) {
try {
/*getting the number of likes*/
String x = request.getParameter("counts");
int c = Integer.parseInt(x);
int count = c;
count = count + 1; //increment the value
Connection conn = DBConnect.connect();
PreparedStatement ps = conn.prepareStatement("UPDATE Likes SET Like1 = ?");
ps.setInt(1, count);
int num = ps.executeUpdate();
if (num > 0) {
HttpSession session = request.getSession();
session.setAttribute("count", count);
response.setIntHeader("Refresh", 3);
response.sendRedirect("index.jsp");
}
} catch (SQLException e) {
System.out.println("Error in update :" + e.getMessage());
}
}
}
}
【问题讨论】:
-
阅读:engineering.harrys.com/2017/06/28/atomic-operations-in-sql.html 和 stackoverflow.com/questions/4358732/…。我们的想法是以确保您的增量是原子的方式编写它。