
develop a servlet to insert the data in the database from our program in the table stored in the database

Insert Data using servlet
1)insert.jsp:
<%@page import="java.sql.*"%> <html> <form method="post" action="../InsertServlet"> <table> <tr><td>Name:</td><td><input type="text" name="name"></td></tr> <tr><td>Address:</td><td><input type="text" name="address"></td></tr> <tr><td></td><td><input type="submit" value="Submit"></td></tr> </table> </form> </html>
2)InsertServlet.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class InsertServlet extends HttpServlet {
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name=req.getParameter("name");
String address=req.getParameter("address");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement st=con.createStatement();
int i=st.executeUpdate("insert into data(name,address) values('"+name+"','"+address+"')");
out.println("Data is inserted successfully");
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.