Home Answers Viewqa JSP-Servlet fetch and insert multiple rows into mysql database using jsp servlet

 
 


Amyn Kapadia
fetch and insert multiple rows into mysql database using jsp servlet
6 Answer(s)      3 months and 4 days ago
Posted in : JSP-Servlet

hello!!! I am building a attendance sheet in which, I am getting data from one jsp form and want inserting it into my mysql database table. but i am having a problem to insert multiple rows into database using a single insert query here is the code of both jsp and servlet

 <%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
  <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <script>
  $(function() {
    $('.datepicker').datepicker();
    $.datepicker.formatDate('dd-mm-yy');
    $('div.ui-datepicker').css({ fontSize: '12px' });
  });
  </script>
        <title>JSP Page</title>
    </head>
    <body>
        <h1 align="center">Employee Attendance</h1>
        <form action="IsertAttendance" method="POST">
            <table align="center" cellspacing="10" border="0">
                <tr><td><strong>Date</strong></td><td><input type='text' class='datepicker' name='date'/></td></tr>
                <tr><td></td><td><strong>ID</strong></td><td><strong>Name</strong></td><td><strong>Status</strong></td></tr>

                <%
                try{
                Class.forName("com.mysql.jdbc.Driver");
                Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/scs","root","root");
                Statement st=con.createStatement();
                String sql="select * from staff";
                ResultSet rs=st.executeQuery(sql);
                while(rs.next()){
                    String id=rs.getString("id");
                    String name=rs.getString("fname");

                %>
                <tr><td></td><td><input type="text"value="<%=id %>" disabled="true" /></td><td><input type="text" value="<%=name %>" name="name" disabled="true"/></td>
            <td><select name="status">
            <option>Present</option>
            <option>Absent</option>
            <option>Leave</option>
            <option>Holiday</option>
        </select></td></tr>


                <% 
                }
                }catch(Exception e){
                out.println(e);
                }
                %>
                <tr><td></td><td></td><td><input type="Submit" value="Submit"/></td></tr>
            </table>    

        </form>
    </body>
</html>

**IsertAttendance.java**

    import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
public class IsertAttendance extends HttpServlet {


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int i;
        try {
            String s1=request.getParameter("date");
            String s2=request.getParameter("id");
            String s3=request.getParameter("name");
            String s4=request.getParameter("status");
                Class.forName("com.mysql.jdbc.Driver");
                Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/scs","root","root");
                Statement st=con.createStatement();
                String sql="insert into attendance(date,id,name,status) values('"+s1+"','"+s2+"','"+s3+"','"+s4+"')";

                st.executeUpdate(sql);

                st.close();
                con.close();
                response.sendRedirect("Attendance.jsp");
        }catch(Exception e){
        out.println(e);
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

this is my database table **attendance**

DROP TABLE IF EXISTS `scs`.`attendance`;
CREATE TABLE  `scs`.`attendance` (
  `date` varchar(30) NOT NULL default '',
  `id` varchar(45) NOT NULL default '',
  `name` varchar(45) NOT NULL default '',
  `status` varchar(45) NOT NULL default '',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Please help me urgently it is my major project..

View Answers

February 18, 2013 at 10:15 AM


hi friend,

First you have done mistaken in your jsp page at

select * from staff

here, you are trying to get the records from unavailable database table.

Second you have done mistaken at

String name=rs.getString("fname");

here, you are trying to get the resultset from the unavailable field.


February 18, 2013 at 8:47 PM


I m right at that... actually i am also getting the records from the staff table and displayed on the jsp and problem is that from that jsp i want to insert all that records into the database


February 19, 2013 at 6:16 PM


hi friend,

To insert multiple records you can use the addBatch() method for executing the multiple insert query.

For detail tutorial please go through the following link, may this will be helpful for you.

http://www.roseindia.net/jdbc/prepared-statement-add-batch.shtml


February 19, 2013 at 7:07 PM


hi friend,

try this code

Attendance.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*" %> 
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" 
href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$('.datepicker').datepicker();
$.datepicker.formatDate('dd-mm-yy');
 //$('.datepicker').datepicker({ dateFormat: 'dd-mm-yy' });
$('div.ui-datepicker').css({ fontSize: '12px' });
});
</script>
<title>JSP Page</title>
</head>
<body>
<h1 align="center">Employee Attendance</h1>
<form action="IsertAttendance" method="POST">
<table align="center" cellspacing="10" border="0">
<tr>
<td></td>
<td><strong>ID</strong></td>
<td><strong>Name</strong></td>
<td><strong>Status</strong></td>
<td><strong>Date</strong></td>
</tr>

<% 
try{ Class.forName("com.mysql.jdbc.Driver"); 
Connection con=DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/record","root","root"); 
Statement st=con.createStatement(); 
String sql="select * from staff"; 
ResultSet rs=st.executeQuery(sql); 
while(rs.next()){ 
    String id=rs.getString("id"); 
    String name=rs.getString("name");   
%>
<input type="hidden" name="id" value="<%= id %>"/>
<input type="hidden" name="name" value="<%= name %>"/>
<tr>
<td></td>
<td><%= id %></td>
<td><%= name %></td>
<td>
<select name="status">
<option>Present</option>
<option>Absent</option> 
<option>Leave</option> 
<option>Holiday</option> 
</select></td>
<td><input type='text' class='datepicker' name='date'/></td>
</tr>
<% 
}
}
catch(Exception e)
{
    out.println(e); 
}
%>
<tr></tr> 
<tr>
<td></td><td></td>
<td><input type="Submit" value="Submit"/></td>
</tr> 
</table>
 </form> 
</body>
</html>

continue.......


February 19, 2013 at 7:09 PM


IsertAttendance.java

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

public class IsertAttendance extends HttpServlet {
    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int i;
        try {
            String[] s1 = request.getParameterValues("date");
            String[] s2 = request.getParameterValues("id");
            String[] s3 = request.getParameterValues("name");
            String[] s4 = request.getParameterValues("status");
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/record", "root", "root");
            Statement st = con.createStatement();
            for(int j= 0; j<s2.length; j++)
            {
            String sql = "insert into attendance(date,id,name,status) values('"
                    + s1[j] + "','" + s2[j] + "','" + s3[j] + "','" + s4[j] + "')";
            st.addBatch(sql);
            }

            st.executeBatch();

            st.close();
            con.close();
            response.sendRedirect("Attendance.jsp");            
        } catch (Exception e) {
            out.println(e);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed"
    // desc="HttpServlet methods. Click on the 
    //+ sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * 
     * @param request
     *            servlet request
     * @param response
     *            servlet response
     * @throws ServletException
     *             if a servlet-specific error occurs
     * @throws IOException
     *             if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * 
     * @param request
     *            servlet request
     * @param response
     *            servlet response
     * @throws ServletException
     *             if a servlet-specific error occurs
     * @throws IOException
     *             if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * 
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

February 20, 2013 at 8:50 PM


no its not working..........

Exception java.lang.ArrayIndexOutOfBoundsException: 1









Related Pages:
fetch and insert multiple rows into mysql database using jsp servlet
fetch and insert multiple rows into mysql database using jsp servlet  ... jsp form and want inserting it into my mysql database table. but i am having a problem to insert multiple rows into database using a single insert query
Displaying Rows - JSP-Servlet
ms sql 2000 database into an html form text box and text area, using java servlet or jsp  Hi friend, This is form code, display data...("Successfully insert data in database"); } catch (SQLException ex
Facing Problem to insert Multiple Array values in database - JSP-Servlet
Facing Problem to insert Multiple Array values in database  Hai... facing the problem while inserting the data in database. iam using the MsAccess Database My Database structure is Like iam using tow tabel ,CustomerDetails
update multiple rows in jsp - JSP-Servlet
update multiple rows in jsp  Hi I am trying to do a multiple row update in JSP. code as follows.. > Can you...,author and title in the database. Follow these steps to update these fields: 1
How to insert rows from Excel spreadsheet into database by browsing the excel file?
excel file and insert rows into MSSQL database in JSP???   Have a look...How to insert rows from Excel spreadsheet into database by browsing the excel...-Servlet/18638-Read-Excel-data-using-JSP-and-update-MySQL-databse.html
fetch record from oracle database using jsp-servlet?
fetch record from oracle database using jsp-servlet?  how can i fetch data from oracle database by using jsp-servlet. i'm using eclipse, tomcat server and oracle database and creating jsp pages and also using servlet
insert rows from browsed file to sql database
insert rows from browsed file to sql database  i need to insert rows from excel to database by browsing the file in jsp. by connecting both..., content of the file has to go to database. how can i insert record into database
Fetch the data using jsp standard action
Fetch the data using jsp standard action  I want the code of fetch the data from the database & show in a jsp page using jsp:usebean in MVC model... that retrieves the data from the database through java bean and display it in jsp page
how to read the values for text and csv files and store those values into database in multiple rows..means one value for one row
into database in multiple rows..means one value for one row  Hai, I need... table in multiple rows(which means one value for one row). eg: my file containes... created this project in eclipse Setup database Here, I used MySql database, so type
insert name city and upload image in database using mysql and jsp
insert name city and upload image in database using mysql and jsp   insert name city and upload image in database using mysql and jsp
save multiple records into database using jsp/servlet mvc
save multiple records into database using jsp/servlet mvc  hai, this is my jsp where i have enter multiple username and password and save... set to bean and pass bean to dao insert() and insert into database thank u
how to fetch image from mysql using jsp
how to fetch image from mysql using jsp  how to fetch image from mysql using jsp
JSP-Mysql - JSP-Servlet
JSP-Mysql  Hello friends, Anyone send me the way how to store image in mysql database from a jsp page.  Hi friend, Code to insert image in mysql Using Jsp : For more information on JSP
insert data in the database using checkbox
insert data in the database using checkbox  i am fetching data from the database using servlet on the jsp page and there is checkbox corresponding... should i insert only checked data into database on submission.   We
insert values - JSP-Servlet
insert values  How to insert values in the oracle database using JSP... page<html><head><title>Insert value in database</title><...;100%"> <h1><center>Insert value in Database<
how to insert multiple columns of a single row into my sql database using jsp
how to insert multiple columns of a single row into my sql database using jsp  hi sir, how to insert multiple columns of a single row into my sql database using jsp. when i click ADD ROW,rows are added.when i click submit
inserting multiple file formats into database
inserting multiple file formats into database  hi i want to insert multiple file format like .pdf.doc.zip into mysql database using jsp
insert rows from Excel sheet into a database by browsing the file
insert rows from Excel sheet into a database by browsing the file  hello, I am trying to insert rows from Excel sheet into SQL database by browsing Excel file in java(JSP). I can insert rows using ODBC connetion. But using odbc
Insert and Retrieve Image - JSP-Servlet
Insert and Retrieve Image  Hello, I need source code using java servlet or jsp and html form and brief explanations on how to insert and retrieve image from Microsoft sql database 2000 not Mysql please as sent to me earlier
how insert multiple images in mysql database with use of struts 1.3.8 or java method, with single bean,or using array
how insert multiple images in mysql database with use of struts 1.3.8 or java method, with single bean,or using array  i am using netbeans 7.0 ,with struts 1.3.8 and i want to insert multiple images in mysql database ,with use
Mysql Multiple Date Insert
Mysql Multiple Date Insert       Mysql Multiple Column Insert is used to add or insert... illustrate an example from 'Mysql Multiple Column Insert'.To understand
Mysql Multiple Date Insert
Mysql Multiple Date Insert       Mysql Multiple Column Insert is used to add or insert... illustrate an example from 'Mysql Multiple Column Insert'. To understand an example
JSP Radio Button MySQL insert - JSP-Servlet
with select lists. I have created a servlet to connect to MySQL database...JSP Radio Button MySQL insert  Hi, I have an HTML form which has... with the code to store radio button data and checkbox data to MySQL table. For example
insert name city image in database using mysql and jsp
insert name city image in database using mysql and jsp  how to insert name ,city and image in database in mysql and jsp   Here is an example in jsp that insert name, city and image to database. <%@ page import
Backup MySQL Database - JSP-Servlet
Backup MySQL Database  Database Sir I have been reading Rose's india tutorial "Using MySQL Database with JSP/Servlet". In the Tutorial you have shown an example of backing up the database. When I tried to backup database
MySQL PHP Insert
the database:".mysql_error()); $sql="insert into mytable (Empid,Empname... MySQL PHP Insert       Mysql PHP Insert is used to execute the Mysql function ( ) insert
How to insert multiple checkboxes into Msaccess database J2EE using prepared statement - Java Beginners
How to insert multiple checkboxes into Msaccess database J2EE using prepared... for different subjects, you can insert the multiple subjects in one column... to resolve my Servlet problem, I still can't resolve it. Hope that you can share
Insert into table using Java Swing
INSERTION IN TABLE USING SWING In this section, We will insert rows into "Mysql" database using "Swing". What is Swing? Swing...:mysql://192.168.10.13:3306/ankdb","root","root");  
PHP SQL Fetch
; PHP SQL Fetch is used to fetch the records from Mysql database to PHP...: Insert into is used to add the records or rows value to the table 'stu'. INSERT...;; $password = "root"; $database = "komal"; $connection = mysql
How to insert multiple drop down list data in single column in sql database using servlet
How to insert multiple drop down list data in single column in sql database using servlet  i want to insert date of birth of user by using separate drop down list box for year,month and day into dateofbirth column in sql server
Multiple upload - JSP-Servlet
Multiple upload  Hello everyone and Deepak i am using jsp and mysql I am using the program published on roseindia.net of Multiple upload and i am facing an error as given below please help and reply soon this is my 8th
insert multiple selection - Java
insert multiple selection - Java  how to insert multiple selection values from html into database using servlets
insert image - JSP-Servlet
insert image  hi friends i am mahesh i am trying to insert image into oracle database using JSP but i am not geting so please friends send me the code for inserting image into database using JSP   Hi Friend, Try
Upload Exce Data into MySql Using Jsp and Servlet - JSP-Servlet
Upload Exce Data into MySql Using Jsp and Servlet  now i am doing... into Mysql Database table so please give the coding to me, it's very urgent for me... the following link: http://www.roseindia.net/jsp/upload-insert-csv.shtml Hope
Insert Image in DB through Servlet - JSP-Servlet
image in Database using servlet to visit.... http://www.roseindia.net... that: I want to add the Image In databse using servlet. I have a program Its fine... in Databse using servlet. On the server prompt Its shows: Can not find
Insert Image In DB through Servlet - JSP-Servlet
image in Database using servlet to visit.... http://www.roseindia.net... that: I want to add the Image In databse using servlet. I have a program Its fine... in Databse using servlet. On the server prompt Its shows: Can not find
Java to insert picture to database - JSP-Servlet
it using Jsp but displayed nothing hence I sent this request. Please help me...Java to insert picture to database  Hi Guys, Please assist me on this. Below is the code I wanted to use to insert picture into Ms Sql server 2000
How to insert image in sql database from user using servlet
How to insert image in sql database from user using servlet  pls tell me accept image from user and insert image in sql server 2005 database using servlet and jsp
JSP edit multiple rows
JSP edit multiple rows In this tutorial, you will learn how to update multiple records at the same time. The given example retrieves the record from... and allow the user to edit that particular record. User can edit multiple rows from
Using MYSQL Database with JSP & Servlets.
Using MYSQL Database with JSP & Servlets.  ... acceres the MYSQL database. Here I am using MYSQL & tomcat server...; In MySQL all the database commands are followed by a semi-colon
how to insert data in database using html+jsp
how to insert data in database using html+jsp  anyone know what...; Here we have used MySQL database: 1)form.html: <html> <form... and database name. Here machine name id localhost and database name
how to insert checkbox value into database using jsp
how to insert checkbox value into database using jsp  How to insert check box value to the oracle database using jsp? I want to create hotel's...;   Here is a simple jsp code that insert the selected checkbox values
Insert a row in 'Mysql' table using JSP Code
Insert a row in 'Mysql' table using JSP Code In this section, we will discuss about how to insert data in Mysql database using JSP code. Query...; Mysql database Table. Code to insert row in Mysql table : databaseinsertion.jsp
Show multiple identical rows into JTable from database
Show multiple identical rows into JTable from database In this tutorial, you will learn how to display the multiple rows from database to JTable. Here is an example that search the data from the database and show multiple identical
insert excel sheet into mysql as a table
insert excel sheet into mysql as a table  sir, i want to import an excel sheet into mysql5.0 database as in the table format using tomcat 6.0 by jsp
insert data into database
insert data into database  hi,thanks for reply just i am doing student information project,frontend is jsp-servlet and backend is msaccess2007. i... and studentmaster is the database table name. i am using same details. Now give
Welcome to the MySQL Tutorials
the database using MySQL and we are forwarding this servlet data to the "... of a query the MySQL performs a join that linking the rows from multiple... Using MYSQL Database This lesson is intended to provide hands
Insert Blob(Image) in Mysql table using JSP
Insert Blob(Image) in Mysql table using JSP In this Section, we will insert blob data(image) in Mysql database table using JSP code. A Blob stores a binary... Blob(Image) in Mysql table using JSP Download Source Code
Insert text into database table using JSP & jQuery
Insert text into database table using JSP & jQuery In this tutorial , the text is inserted into database table using JSP & jQuery. In the below... using "fadeIn" effect. The second JSP page contains code
PHP SQL Insert
; database using PHP. Understand with Example The Tutorial illustrate... to the database and submit the records from HTML page with PHP post variable. The Mysql... = "root"; $database = "komal"; $connection = mysql_connect

Ask Questions?

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.