简体   繁体   中英

insert and update in mysql table using JDBC

There are two tables in my database (filedetails and filestatus).

I using the following code to insert value in filedetails table.

In filestatus table i have 3 columns

filenumber,
fdepartment,
status(either in or out).

In my status.jsp page I have given 3 dropdown list in which 2 dropdownlist take filenumber and department from filedetails table and 1 takes status(which is either IN or OUT).

If status is OUT values are simply inserted in filestatus table but if it is in the values are inserted into filestatus and department corresponding to filenumber gets updated.

The problem is the filenumber , if i use the following code to insert filenumber then how will i update the file number ?

Is ther some other way to do this?

file.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert File Page</title>
    <style>
header {
background-color:teal;
color:white;
text-align:center;
padding:30px;
}

section {
width:350px;
float:left;
padding:150px;
}
footer {
background-color:black;
color:white;
clear:both;
text-align:center;
padding:5px;
}
</style>
</head>
<body style="background-color:lightsteelblue;">
   <%
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
%>
<header>
<h3>Hi <%=userName %></h3>
</header>
<a href="create.jsp"><font color="black">back</font></a>
<form action=" LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
<section>
<form action="FileServlet" method="post">
<h3>Insert File Details</h3>
    <table border="1">
        <tbody>
            <tr>
                <td>File Name :</td>
                <td><input type="text" name="filename" value="" size="50"    /></td>
            </tr>
            <tr>
                <td>File Type</td>
                <td><input type="text" name="type" value="" size="50" />  </td>
            </tr>
            <tr>
                <td>Place of Origin(company) :</td>
                <td><input type="text" name="company" value="" size="50"   /></td>
            </tr>
            <tr>
                <td>HeadOffice :</td>
                <td><input type="text" name="HO" value="" size="50" /> </td>
            </tr>
            <tr>
                <td>File Location :</td>
                <td><input type="text" name="department" value="" size="50" />  </td>
            </tr>
            <tr>
                <td>Subject :</td>
                <td><input type="text" name="subject" value="" size="50"   /></td>
            </tr>
            <tr>
                <td>File Number :</td>
                <td><input type="text" name="fileno" value="" size="50"   /></td>
            </tr>

        </tbody>
    </table>
    <input type="reset" value="Clear" name="Clear" />
    <input type="submit" value="Submit" name="Submit" />

</form>
</section>
<footer>
Copyright 2008 NSIC. All right reserved.   
</footer>
</body>
</html>

fileServlet.java

package bean;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class FileServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
   Cookie[] cookies = request.getCookies();
    if(cookies != null){
    for(Cookie cookie : cookies){
        if(cookie.getName().equals("JSESSIONID")){
            System.out.println("JSESSIONID="+cookie.getValue());
            break;
        }
    }
    }       
    HttpSession session = request.getSession(false);
    System.out.println("User="+session.getAttribute("user"));
   if(session!=null && session.getAttribute("user") != null){
                String user=(String)session.getAttribute("user"); 

          boolean status=false;
    try{            
        String fname=request.getParameter("name");            
        String type=request.getParameter("type");
        String company=request.getParameter("department");
        String headoffice=request.getParameter("HO"); 
        String location=request.getParameter("department");
        String subject=request.getParameter("subject");            
        String fno=company+"/"+headoffice+"/"+location+"/"+type+"/"+fname;


        Connection con=ConnectionProvider.getCon();
        String sql="insert into files(fileno,fname,ftype,subject,company,headoffice,fdepartment) values (?,?,?,?,?,?)";
        PreparedStatement pstmt =con.prepareStatement(sql);

        pstmt.setString(1,fno); 
        pstmt.setString(2,fname);
        pstmt.setString(3,type);
        pstmt.setString(4,subject); 
        pstmt.setString(5,company);
        pstmt.setString(6,headoffice);
        pstmt.setString(7,location);

        int rs=pstmt.executeUpdate();
        if(rs>0){status=true;}
    }catch(Exception e){System.out.println(e);}
    if(status){
               PrintWriter out= response.getWriter();
               out.println("Values have been inserted"+user);
               response.sendRedirect("create1.jsp");

    }
               else 
              {
                  PrintWriter out= response.getWriter();
                  out.println("failed");
                  response.sendRedirect("create1.jsp");

              }                                
    }else{
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.html");
    PrintWriter out= response.getWriter();
    out.println("<font color=red>Either user name or password is wrong.</font>");
    rd.include(request, response);
    }
}
}

There is create.jsp which gives link to choose for filedetails.jsp or status.jsp

status.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">
    <title>File Status Page</title>
     <style>
header {
background-color:teal;
color:white;
text-align:center;
padding:30px;
}

section {
width:350px;
float:left;
padding:150px;
}
footer {
background-color:black;
color:white;
clear:both;
text-align:center;
padding:5px;
}
</style>
</head>
<body style="background-color:lightsteelblue;">
     <%
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
%>
<header>
<h3>Hi <%=userName %></h3>
</header>
<a href="create.jsp"><font color="black">back</font></a>
<form action=" LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
<section>
<h3>Change Status</h3>
<form action="statusServlet" method="post">
        <select name="files">
                <%
    try{
String sql="select * from files";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/login",
        "root", "root");
Statement st = con.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
%>                          
  <option value="<%=rs.getInt("fileno")%>"><%=rs.getString("fname")%></option>
<%}
rs.close();
st.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
%> 
        </select>
        <select name="departments">
            <%
    try{
String sql="select * from department";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/login",
        "root", "root");
Statement st = con.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
%>                          
  <option value="<%=rs.getInt("departmentid")%>"><%=rs.getString("departmentname")%></option>
<%}
rs.close();
st.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
%>
        </select>
        <select name="input">
            <option>IN</option>
            <option>OUT</option>
        </select>
        <input type="submit" value="submit" name="submit" />
    </form>
</section>
<footer>
Copyright 2008 NSIC. All right reserved.                             
</footer>
</body>
</html>

I have not yet created statusServlet.java

I will seperate department into two parts like below.

1) Department from which the file is being originated

2) Current location of file.

I will use the file origin department for generating the filenumber and will update the current location separately (Initially the current location will be same as origin department).

If anyone having more effective way than this, then I will accept that too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM