------两天前--------
我只为一个网站的“喜欢”建立了一个数据库。数据库有一个表(likes)和几个字段(like1、like2等…)
在一个jsp文件中,我建立了连接并显示了一个字段的值(如1)。
但我想做的是:通过单击某个文本,值增加1,将数据库中的值从like1更新为like1+1。”
---编辑---
单击按钮时,显示以下内容:
错误
刷新时,数据不会更改。所以我想如果我不显示错误,它会工作。
我想要的是,当你按下按钮时,db data增量为1。
结构:
结构
索引.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>
数据库连接.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());
}
}
}
}
1条答案
按热度按时间2ledvvac1#
在这种情况下,您将需要一个servlet和一个数据库连接类。
首先,这是数据库连接类。数据库连接.java
接下来,这将是index.jsp表单
最后是servlet。likecount.java类
希望能成功。