使用jsp dao和servlet在数据库中仅插入4行中的几行

时间:2015-11-17 08:31:35

标签: java mysql jsp servlets

我有一个名为activitylog的数据库表,其中包含empid,date,card no,start time,end time。

我想只插入几行非空或空以插入mysql数据库。

我知道如何一次插入一行或所有行,但我想只插入几行。请告诉我怎么做。

的index.jsp

<form action="ActivityServlet" method="post">
<h2>ACTIVITY LOG</h2><br>
<table border="1" id="t01"><thead class="ui-widget-header">
    <tr><th>Employee ID</th><th>Date</th><th>CRO/Job Card No.</th><th>Start Time</th><th>End Time</th><th>Category</th></tr>
    </thead>
        <tbody class="ui-widget-content">

            <tr>
                <td><input type="text" name="empid1" value=""/></td>   
                <td><input type="date" class="date" name="activitydate1"/></td>  
                <td><input type="text" name="cardno1" /></td>  
                <td><input type="time" name="starttime1"/></td>  
                <td><input type="time" name="endtime1"/></td> 
                <td><input type="text" name="category1"/></td>  

            </tr>  
            <tr>
                <td><input type="text" name="empid2" value=""/></td>   
                <td><input type="date" class="date" name="activitydate2"/></td>  
                <td><input type="text" name="cardno2" /></td>  
                <td><input type="time" name="starttime2"/></td>  
                <td><input type="time" name="endtime2"/></td> 
                <td><input type="text" name="category2"/></td>  

            </tr>  
<tr>
                <td><input type="text" name="empid3" value=""/></td>   
                <td><input type="date" class="date" name="activitydate3"/></td>  
                <td><input type="text" name="cardno3" /></td>  
                <td><input type="time" name="starttime3"/></td>  
                <td><input type="time" name="endtime3"/></td> 
                <td><input type="text" name="category3"/></td>  

            </tr>  
<tr>
                <td><input type="text" name="empid4" value=""/></td>   
                <td><input type="date" class="date" name="activitydate4"/></td>  
                <td><input type="text" name="cardno4" /></td>  
                <td><input type="time" name="starttime4"/></td>  
                <td><input type="time" name="endtime4"/></td> 
                <td><input type="text" name="category4"/></td>  

            </tr>  

    </tbody>
</table>  
<br><br>
<input class="myButton" type="submit" value="Submit">
<a href="logout.jsp" class="myButton">Logout</a>
</form> 

ActivityDao:

import com.eis.bean.ActivityBean;
import com.eis.bean.ConnectionProvider;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import java.sql.*;
public class ActivityDao {
 public static final String sql= "insert into activitylog values(?,?,?,?,?,?,?,?,?)";

        public static int activity(List<ActivityBean> ebList) throws Exception {
            int i[] = null;
            PreparedStatement ps=null;
            System.out.println("In TimesheetDao");
            Connection conn=ConnectionProvider.getConn();

             ps = conn.prepareStatement(sql);

            try{ 
                System.out.println(" in try in Timesheetdao");
                conn.setAutoCommit(false);
                for  (ActivityBean activitylog: ebList){
                ps.setString(1,activitylog.getEmpid());
                ps.setDate(2,new Date(activitylog.getActivitydate().getTime()));
                ps.setString(3,activitylog.getCardno());  
                ps.setString(4,activitylog.getStarttime()); 
                ps.setString(5,activitylog.getEndtime());
                ps.setString(6,activitylog.getCategory());  
                ps.setString(7,activitylog.getActivity()); 
                ps.setString(8,activitylog.getTraveltime());
                ps.setString(9,activitylog.getRepairtime());

                ps.addBatch();
                }
                 i= ps.executeBatch();
                conn.commit();


                }
             catch (SQLException e) {
                            System.out.println(e.getMessage());
                            conn.rollback();
                    }
            finally { 
                if (conn != null) {  
                    try {  
                        conn.close();  
                    } catch (SQLException e) {  
                        e.printStackTrace();  
                    }  
                }
                if (ps != null) {  
                    try {  
                        ps.close();  
                    } catch (SQLException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  

    return  i[0];
        }
    }

AvtivityServlet.java

public class ActivityServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

private ActivityDao dao;
public ActivityServlet() {
    super();
    dao = new ActivityDao();
}

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException,ParseException  {


    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    List<ActivityBean> ebList=  new ArrayList<ActivityBean>();
for(int i=1;i<=4;i++){
    ActivityBean ab = new ActivityBean();
    ab.setEmpid(request.getParameter("empid"+i));

    ab.setActivitydate((java.sql.Date) new java.sql.Date(formatter.parse(request.getParameter("activitydate"+i)).getTime()));
    ab.setCardno(request.getParameter("cardno"+i));
    ab.setStarttime(request.getParameter("starttime"+i));
    ab.setEndtime(request.getParameter("endtime"+i));
    ab.setCategory(request.getParameter("category"+i));
    ab.setActivity(request.getParameter("activity"+i));
    ab.setTraveltime(request.getParameter("traveltime"+i));
    ab.setRepairtime(request.getParameter("repairtime"+i));
    ebList.add(ab);

     }

HttpSession session = request.getSession(false); 
ActivityDao dao = new ActivityDao();

try {

   int status = ActivityDao.activity(ebList);

if(status!=0){
    out.print("<p style=\"color:Green\">Record saved successfully!!</p>");  
    RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");    
    rd.include(request,response);
}
else{    
    out.print("<p style=\"color:red\">**Record cannot be saved!**</p>");    
    RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");    
    rd.include(request,response);
}

 }
catch(Exception e){
   e.printStackTrace();
}
}

只有bean类。 上面的代码是4行。它将被插入数据库中。但我想知道如何只插入几行示例2或3行,然后我就不能这样做了。请帮帮我。

错误:

 17-Nov-2015 11:42:16.937 SEVERE [http-apr-8080-exec-145] com.eis.servlet.ActivityServlet.doPost null
 java.text.ParseException: Unparseable date: ""
        at java.text.DateFormat.parse(DateFormat.java:366)
        at com.eis.servlet.ActivityServlet.processRequest(ActivityServlet.java:53)
        at com.eis.servlet.ActivityServlet.doPost(ActivityServlet.java:119)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
        at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2503)
        at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2492)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)

1 个答案:

答案 0 :(得分:0)

一种解决方案是检查DAO中的空值。

示例:

for  (ActivityBean activitylog: ebList){
    if(activitylog.getCardno==null){
        ps.setString(1,activitylog.getEmpid());
        ps.setDate(2,new Date(activitylog.getActivitydate().getTime()));
        ps.setString(3,activitylog.getCardno());  
        ps.setString(4,activitylog.getStarttime()); 
        ps.setString(5,activitylog.getEndtime());
        ps.setString(6,activitylog.getCategory());  
        ps.setString(7,activitylog.getActivity()); 
        ps.setString(8,activitylog.getTraveltime());
        ps.setString(9,activitylog.getRepairtime());
        ps.addBatch();
    }
}

在这里检查cardNo是否为空。您可以在那里进行所有类型的检查,并根据您的标准限制INSERT的数量