Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

saving data to a database via servlet  RSS feed

Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i want so save data from html page to database using servlet.
see my servlet and find if there is any mistake. beacause it does not work.
// import packages
import java.awt.*;
import java.sql.*;
import javax.servlet.*;
import javax.swing.*;
import java.awt.event.*;
import javax.servlet.http.*;

public class AddProduct extends HttpServlet
public void init(ServletConfig config) throws ServletException{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String connectionURL ="jdbcdbc:ProductDSN";
Connection connection=null;
ResultSet rs;

String pID = request.getParameter("pID");
String name = request.getParameter("pName");
String category = request.getParameter("category");
String price = request.getParameter("price");
String availability = request.getParameter("availability");
String quantity = request.getParameter("quantity");
String description = request.getParameter("description");


String url = "jdbcdbc:ProductDSN";
Connection conn = DriverManager.getConnection(url,"","");
Statement st = conn.createStatement();
String sql = "Insert into Product(id,productName,category,price,availability,quantity,description) values(?,?,?,?,?,?,?) ";
java.sql.PreparedStatement pst =conn.prepareStatement(sql);
pst.setString(1, pID);
pst.setString(2, name);
pst.setString(3, category);
pst.setString(4, price);
pst.setString(5, availability);
pst.setString(6, quantity);
pst.setString(7, description);


catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);


// web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>



Author and ninkuma
Posts: 66425
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please give us more information about what is not working. See ItDoesntWorkIsUseless
Posts: 23281
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If any exception is thrown in your code, then at best a dialog box will appear on your server, where nobody will see it. It's also possible that the server will be running headless, in which case the dialog box will have nowhere to appear. What you should do instead is this:

This will cause the stack trace of the exception to be written to your server's logs. You should already be looking there to see what you can find out, too.
Ranch Hand
Posts: 515
Eclipse IDE Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Faisal Shahzad,

Try the working example here:

Upload files to database (Servlet + JSP + MySQL)
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!