1 Replies - 27883 Views - Last Post: 17 December 2010 - 09:02 AM

#1 xinvux   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 07-October 09

Servlet to insert data to a database

Posted 16 December 2010 - 10:51 PM

I hope I'm in the right section. Well, I am developing a web site for a class and I'm trying to make a servlet that will take the user input from a form and insert those inputs into a database. My professor gave me a sample code in which he said I would have to modify to fit my need. I changed everything that I think I should be changing but it's not working. Can anyone tell me what I did wrong? I want to insert the data into the database and then post the inserted data on a web page. Example: if i put first name and last name on the form, after I click submit, a new page should display First Name: xinvux Last Name: x (something like that)
I AM VERY NEW AT THIS. My knowledge in java is close to nothing. Please help!!!
Well, here the code: (
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Register;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Karine
 */
public class Register extends HttpServlet {
  @Override
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String docType =
      "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
      "Transitional//EN\"\n";
    String title = "Search Results";
    out.print(docType +
              "<HTML>\n" +
              "<HEAD><TITLE>" + title + "</TITLE>" +
             "<link href=../styles/styles.css rel=\"stylesheet\" type=\"text/css\">\n" +
             "</HEAD>\n" +
             "<BODY BGCOLOR=\"#FDF5E6\"><CENTER>\n" +
             "<H1>Search Results</H1>\n");
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    String url = "jdbc:odbc:bookworm";
    String userName = "root";
    String password = "admin";
    //String isbn = request.getParameter("search");
    String fname = request.getParameter("fname");
    String lname = request.getParameter("lname");
    String email = request.getParameter("email");
    String pass = request.getParameter("pass");
    String address = request.getParameter("address");
    String city = request.getParameter("city");
    String state = request.getParameter("state");
    String country = request.getParameter("country");
    String zip = request.getParameter("zip");
    String phone = request.getParameter("phone1");

    showTable(driver, url, userName, password, fname, lname, email, pass,
            address, city, state, country, zip, phone, out);
    out.println("</CENTER></BODY></HTML>");
  }

    public void showTable(String driver, String url,
                        String username, String password,
                        String fname, String lname, String email,
                        String pass, String address, String city, String state,
                        String country, String zip, String phone,
                        PrintWriter out) {

        try {
      // Load database driver if it's not already loaded.
      Class.forName(driver);
      // Establish network connection to database.
      Connection connection =
        DriverManager.getConnection(url, username, password);
      // Look up info about the database as a whole.
      DatabaseMetaData dbMetaData = connection.getMetaData();
      out.println("<UL>");

      String productName =
        dbMetaData.getDatabaseProductName();

      String productVersion =
        dbMetaData.getDatabaseProductVersion();
      out.println("  <LI><B>Database:</B> " + productName +
                  "  <LI><B>Version:</B> " + productVersion +
                  "</UL>");
      Statement statement = connection.createStatement();
      // Send query to database and store results.

      //String query = null;


       String query = "INSERT INTO Customers(FirstName,LastName,Address,City,Add_State,Country,ZipCode,PhoneNumber,EmailAddress,Password)"
               + "VALUES ("+fname+","+lname+","+address+","+city+","+state+","+country+","+zip+","+phone+","+email+","+pass+")";

      ResultSet resultSet = statement.executeQuery(query);
      // Print results.
      out.println("<TABLE BORDER=1>");
      ResultSetMetaData resultSetMetaData =
        resultSet.getMetaData();
      int columnCount = resultSetMetaData.getColumnCount();
      out.println("<TR>");
      // Column index starts at 1 (a la SQL), not 0 (a la Java).
      for(int i=1; i <= columnCount; i++) {
        out.print("<TH>" + resultSetMetaData.getColumnName(i));
      }
      out.println();
      // Step through each row in the result set.
      while(resultSet.next()) {
        out.println("<TR>");
        // Step across the row, retrieving the data in each
        // column cell as a String.
        for(int i=1; i <= columnCount; i++) {
          out.print("<TD>" + resultSet.getString(i));
        }
        out.println();
      }
      out.println("</TABLE>");
      out.println("<div align=\"center\">\n"+
              "<a href=\"homepage3.jsp\"/>Please click here to go back to Homepage.</div>");
      connection.close();
    } catch(ClassNotFoundException cnfe) {
      System.err.println("Error loading driver: " + cnfe);
    } catch(SQLException sqle) {
      System.err.println("Error connecting: " + sqle);
    } catch(Exception ex) {
      System.err.println("Error with input: " + ex);
    }
  }

  private static void showResults(ResultSet results)
      throws SQLException {
    while(results.next()) {
      System.out.print(results.getString(1) + " ");
    }
    System.out.println();
  }

  private static void printUsage() {
    System.out.println("Usage: PreparedStatements host " +
                       "dbName username password " +
                       "vendor [print].");
  }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Servlet to insert data to a database

#2 KYA   User is offline

  • Wubba lubba dub dub!
  • member icon

Reputation: 3209
  • View blog
  • Posts: 19,240
  • Joined: 14-September 07

Re: Servlet to insert data to a database

Posted 17 December 2010 - 09:02 AM

I see your data gathering and insert, but where do you query [aka SELECT] the database for this information?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1