JSP: How to increase a value of a database in JSP?


JSP: How to increase a value of a database in JSP?



I made a database only for the "likes" of a website. The database has a table (Likes) with several fields (Like1, Like2, etc ...)



In a JSP file I made the connection and show the value of a field (Like1).



But what I want to do is: by clicking on a certain text, the value increases by one, updating that value in the database from Like1 to Like1 + 1.



This is my JSP.


<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>




TEXTO DONDE QUISIERA QUE INCREMENTE AL HACER CLICK.














I would be grateful to anyone who can help me. Thank you! and sorry if my English is bad.





Read this: engineering.harrys.com/2017/06/28/atomic-operations-in-sql.html and stackoverflow.com/questions/4358732/…. The idea is to write it in a way that makes sure your increment is atomic.
– Nic3500
1 hour ago




1 Answer
1



Try,


<form method="post">

<button name="click">TEXTO DONDE QUISIERA QUE INCREMENTE AL HACER CLICK.</button>

<%
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/likes";
String username = "root";
String password = "";
String query = "SELECT Like1 from Likes";
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
%>
<br><br>
<!-- <%/*out.println(rs.getInt("Like1")); */%> -->
<%int count = rs.getInt("Like1");
count = count + 1;
PreparedStatement pstmt = conn.prepareStatement("UPDATE Likes SET Like1 = ?");
pstmt.setInt(1, count);
int x = pstmt.executeUpdate();
if (x > 0) {%>
<%out.println(rs.getInt("Like1")); %>
<%}
%></b>

<% }
%>

<%
rs.close();
stmt.close();
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
%>

</form>






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages