I apologize for the misunderstanding. If you want to insert the retrieved data into a table present in the Servlet file, you can use a PreparedStatement to execute an insert statement. Here's an updated version of the code:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/InsertDataServlet")
public class InsertDataServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Database credentials
private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "root";
private static final String PASS = "password";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection conn = null;
PreparedStatement stmt = null;
PrintWriter out = response.getWriter();
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
stmt = conn.prepareStatement("SELECT id, name, age FROM mytable");
ResultSet rs = stmt.executeQuery();
// Print table with retrieved data
out.println("<html><body><table>");
out.println("<tr><th>ID</th><th>Name</th><th>Age</th></tr>");
// Insert data into the table
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// Prepare SQL statement to insert data
PreparedStatement insertStmt = conn.prepareStatement("INSERT INTO mytable (id, name, age) VALUES (?, ?, ?)");
insertStmt.setInt(1, id);
insertStmt.setString(2, name);
insertStmt.setInt(3, age);
// Execute insert statement
insertStmt.executeUpdate();
// Print row with retrieved data
out.println("<tr><td>" + id + "</td><td>" + name + "</td><td>" + age + "</td></tr>");
}
out.println("</table></body></html>");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
out.println("Error: " + e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
In the updated code, we're retrieving data from the mytable table using a PreparedStatement and then inserting that data back into the same table. Additionally, we're dynamically generating an HTML table to display the retrieved data in the response.
Please make sure to replace DB_URL, USER, and PASS with your MySQL database credentials. Also, don't forget to add the MySQL JDBC driver JAR file to your project's classpath.