insert and update in mysql table using JDBC - java

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>
<font color="black">back</font>
<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>
<font color="black">back</font>
<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.

Related

Why retrieve Data is not Update in jsp

I have three JSP as follows:
Employee_vendor_approve.jsp : which is retrieve Employee Details
update_employeeVendorLoginCredentials.jsp: Which is take reference of Employee_vendor_approve.jsp page for upadate process
update_process_employeeVendorLoginCredentials.jsp: is update retrieve data
from point 1 i can able to retrieve data but i unable to proceed point 2 and 3. where is problem i unable to find, when i click update link on Employee_vendor_approve.jsp, update_employeeVendorLoginCredentials.jsp showing blank here is my code
Employee_vendor_approve.jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee and vendor approve Page</title>
</head>
<body>
<table border="1" align="center">
<tr>
<td>FIRST_NAME </td>
<td>LAST_NAME</td>
<td>ORGANIZATION_NAME</td>
<td>EMPLOYEE_ID</td>
<td>Approve</td>
<td>Status</td>
</tr>
<%
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con==DriverManager.getConnection("jdbc:oracle:thin:#173.18.114.213:1821:godb","ex","xe");
statement=con.createStatement();
String Sql="SELECT FIRST_NAME,LAST_NAME,ORGANISATION_NAME,EMPLOYEE_ID,APPROVE from REGISTRATION_EMPLOYEE where role in ('Employee','Vendor')";
resultSet=statement.executeQuery(Sql);
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("FIRST_NAME")%></td>
<td><%=resultSet.getString("LAST_NAME")%></td>
<td><%=resultSet.getString("ORGANISATION_NAME")%></td>
<td><%=resultSet.getString("EMPLOYEE_ID")%></td>
<td><%=resultSet.getString("APPROVE")%></td>
<td>
update
</td>
</tr>
<%
}
//con.close();
%>
</table>
</body>
</html>
update_employeeVendorLoginCredentials.jsp:
<html>
<body>
<form method="post" action="update_process_employeeVendorLoginCredentials.jsp">
<table border="1">
<tr>
<th>FIRST_NAME </th>
<th>LAST_NAME</th>
<th>ORGANIZATION_NAME</th>
<th>EMPLOYEE_ID</th>
<th>Approve</th>
</tr>
<%
String employee_id=request.getParameter("employee_id");
int sumcount=0;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#173.18.114.213:1821:godb","ex","xe");
Statement st=con.createStatement();
String query="SELECT FIRST_NAME,LAST_NAME,ORGANISATION_NAME,EMPLOYEE_ID,APPROVE from REGISTRATION_EMPLOYEE where EMPLOYEE_ID="+employee_id;
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
%>
<tr>
<td><input type="text" name="FIRST_NAME" value="<%=rs.getString("FIRST_NAME")%>"> </td>
<td><input type="text" name="LAST_NAME" value="<%=rs.getString("LAST_NAME")%>"> </td>
<td><input type="text" name="ORGANISATION_NAME" value="<%=rs.getString("ORGANISATION_NAME")%>"> </td>
<td><input type="text" name="APPROVE" value="<%=rs.getString("APPROVE")%>"> </td>
<td><input type="hidden" name="EMPLOYEE_ID" value="<%=rs.getString(1)%>"></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Update" style="background-color:#49743D;font-weight:bold;color:#ffffff;"></td>
</tr>
<% }
}
catch(Exception ex)
{
}
%>
</table>
</form>
</body>
</html>
update_process_employeeVendorLoginCredentials.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#173.18.114.213:1821:godb","ex","xe");
String EMPLOYEE_ID=request.getParameter("EMPLOYEE_ID");
String first_name=request.getParameter("FIRST_NAME");
String Last_name=request.getParameter("LAST_NAME");
String ORGANISATION_NAME=request.getParameter("ORGANISATION_NAME");
String Approve_status=request.getParameter("APPROVE");
if (EMPLOYEE_ID!=null)
{
// Connection con = null;
PreparedStatement ps = null;
int personID = Integer.parseInt(EMPLOYEE_ID);
try
{
String Sql="update REGISTRATION_EMPLOYEE set APPROVE='Y' where EMPLOYEE_ID="+EMPLOYEE_ID;
ps=con.prepareStatement(Sql);
ps.setString(1, Approve_status);
int i=ps.executeUpdate();
if(i>0)
{
out.print("Record Updated Successfully");
}
else
{
out.print("There is a problem in updating Record.");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
%>
</body>
</html>
In Employee_vendor_approve.jsp: you set parameter name called id
update
but in update_employeeVendorLoginCredentials.jsp you get the parameter via employee_id
String employee_id=request.getParameter("employee_id");
They do not keep the same,so you get empty value.In order to solve this,you can change it to below:
String employee_id=request.getParameter("id");//using id instead of employee_id
To the problem you can not update data,it's also due to you fetch wrong value in update_employeeVendorLoginCredentials.jsp:
<td><input type="hidden" name="EMPLOYEE_ID" value="<%=rs.getString(1)%>"></td> // you have get the wrong value for id
In order to let it work,change it as below:
<td><input type="hidden" name="EMPLOYEE_ID" value="<%=rs.getString("EMPLOYEE_ID")%>"></td>

sql syntax error (using jstl tags)

I am taking username, column name and new entry to be updated from user in a jsp.
I am trying to update my SQL database table using jstl tags and also show the updated table.
The jsp page is not opening it is giving a message of syntax error in my update sql query.
my jsp page:-
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import="java.io.*,java.util.*,java.sql.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Found page</title>
<style>
a:link, a:visited {
background-color:darkolivegreen;
color: white;
padding: 10px 25px;
text-align: center;
width:100px;
text-decoration: none;
display: inline-block;
border-radius:20px;
}
a:hover, a:active {
background-color: lightgreen;
}
header {
background-color:teal;
color:white;
text-align:center;
padding:5px;
}
#file {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#file td, #file th {
border: 2px solid black;
text-align: left;
padding: 8px;
}
#file tr:hover {background-color: #ddd;}
#file th {
padding-top: 12px;
padding-bottom: 12px;
background-color: lightslategray;
color: white;
}
section {
height:270px;
width:1050px;
float:right;
padding:87px;
}
footer {
background-color:black;
float:bottom;
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>
<h1>File Tracking System</h1>
<div><span style="float:right">Hi <%=userName%></span></div>
<br>
<form style="float:right" action=" LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
<br>
</header>
<br>
1.Insert New File
2.Change File Status
3.Search your File
4.Check File Status
<br>
<br>
<form method="POST">
User ID:<br><input type="text" name="user" value="" size="20" />
These options in dropdown list the spelling is same as my column name in userdetails table
Alter:<br><select name="use">
<option>userName</option>
<option>password</option>
<option>role</option>
<option>firstname</option>
<option>lastname</option>
<option>departmentname</option>
<option>email</option>
<option>mobile</option>
</select>
New Entry:<br><input type="text" name="enter" value="" size="20" />
<input type="submit" value="submit" name="submit" />
</form>
<br>
<section>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/login"
user="root" password="root"/>
udate sql query-
It is in the form ( update table_name set table_column="xyz" where column_name= "abc"; )
<sql:update dataSource="${snapshot}" var="result">
update usertable set "${param.use}"="${param.enter}" where username="${param.user}";
</sql:update>
<sql:query dataSource="${snapshot}" var="result">
select * from usertable where username="${param.user}";
</sql:query>
<table id="file">
<tr>
<th>UserName</th>
<th>Password</th>
<th>Role</th>
<th>First Name</th>
<th>Last Name</th>
<th>Department Name</th>
<th>Email</th>
<th>Mobile Number</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.username}"/></td>
<td><c:out value="${row.password}"/></td>
<td><c:out value="${row.role}"/></td>
<td><c:out value="${row.firstname}"/></td>
<td><c:out value="${row.lasttname}"/></td>
<td><c:out value="${row.departmentname}"/></td>
<td><c:out value="${row.email}"/></td>
<td><c:out value="${row.mobile}"/></td>
</tr>
</c:forEach>
</table>
</section>
<footer>
Copyright 2016 NSIC. All right reserved.
</footer>
</body>
</html>
what should be the correct syntax for sql? Is there some other way i could do this?
I used an alternate way where i submit values in alter.jsp and get them in a servlet changeServlet.java but it does not show any error and is not getting redirected anywhere it is simply opening http://localhost:8080/test9/changeServlet and is stuck here showing a white blank page.
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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 changeServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//request.getRequestDispatcher("link.html").include(request, response);
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("admin="+session.getAttribute("admin"));
if(session!=null && session.getAttribute("admin") != null){
String admin=(String)session.getAttribute("admin");
boolean status=false;
try{
String user=request.getParameter("user");
String column=request.getParameter("column");
String data=request.getParameter("data");
boolean checkc=checkchar.value(column);
boolean checkp=checkchar.value(data);
the if statement is checking for any wrong entry or null value when submit wrong entry it redirects to entry.jsp. This means it is working till here but after this not working.
if(checkc==true&&checkp==true) {
Connection con=ConnectionProvider.getCon();
String sql="update usertable set '"+column+"'='"+data+"' where username='"+user+"'";
PreparedStatement pstmt =con.prepareStatement(sql);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
if(status){
PrintWriter out= response.getWriter();
out.print("data updated,"+admin);
response.sendRedirect("updated.jsp");
}
else
{
PrintWriter out= response.getWriter();
out.print("failed to update");
response.sendRedirect("notinsert.jsp");
}
}
else{response.sendRedirect("entry.jsp");}
}catch(SQLException e){}
}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);
}
}
}
Your query will not work until these things are modified:
your option tag
<option value="userName">userName</option>
<option value="password">password</option>
<option value="role">role</option>
<option value="firstname">firstname</option>
<option value="lastname">lastname</option>
<option value="department">departmentname</option>
<option value="email">email</option>
<option value="mobile">mobile</option>
You are directly firing query on same page, i.e, you have shown the box, and immediately after it your query is there for update.
this causes problem because JSTL always runs first at server side so it doesn't matter where you write it, it will be executed first, now while executing that query, jstl founds that the parameters are null, so now query becomes something like this.:-
UPDATE TABLE `table-name` SET `null`=null where `user-name`=null;`
you can see in null=null column-name is itself being null, one can consider for null values but your column name too is null, and that doesn't exist in database or table.
so please make it in two jsp pages one will collect info and pass them as parameter to another jsp page, now this page must contain query, now it can fetch parameters value in query properly.

Search inside table MySql database with JSB

I'm a beginner programmer, I already build page for data entry and page show all entries, but now I want to show specific row inside the table, which code can help me?
My table columns: fullname - email - Phone - education
I want to search by email to show the other data in one page.
I found this code on internet:
<%#page import="java.sql.*"%>
<% Class.forName("com.mysql.jdbc.Driver");%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%!
public class Showit {
String URL = "jdbc:mysql://localhost/regdata";
String USERNAME = "root";
String PASSWORD = "admin";
Connection conn = null;
PreparedStatement selectRegister = null;
ResultSet resultSet = null;
public Showit() {
try {
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
selectRegister = conn.prepareStatement(
"SELECT a.fullname, a.email,"
+ " FROM mainr a,"
+ "WHERE a.fullname = ?"
+ "AND a.email = ?");
} catch (Exception e) {
e.printStackTrace();
}
}
public ResultSet getShowit(String fullname, String email) {
try {
selectRegister.setString(1, fullname);
selectRegister.setString(2, email);
resultSet = selectRegister.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
return resultSet;
}
}
%>
<%
String fullname = new String();
String email = new String();
if (request.getParameter("fullname") != null) {
fullname = request.getParameter("fullname");
}
if (request.getParameter("email") != null) {
fullname = request.getParameter("email");
}
Showit showit = new Showit();
ResultSet showits = showit.getShowit(fullname, email);
%>
<table border="1">
<tbody>
<tr>
<td>Full Name</td>
<td>Email</td>
<td>Title</td>
</tr>
<% while (showits.next()) {%>
<tr>
<td><%= showits.getString("fullname")%></td>
<td><%= showits.getString("email")%></td>
<td><%= showits.getString("Phone")%></td>
</tr>
<% }%>
</tbody>
</table>
</body>
</html>
which connect with this page:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.Scanner" %>
<% Class.forName("com.mysql.jdbc.Driver");%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Search</title>
</head>
<body>
<form name="search" action="display.jsp" method="POST">
<table border="0">
<tbody>
<tr>
<td>Full Name</td>
<td><input type="text" name="fullname" value="" size="50" /></td>
</tr>
<tr>
<td>E-Mail</td>
<td><input type="text" name="email" value="" size="50" /></td>
</tr>
</tbody>
</table>
<input type="reset" value="Reset" name="reset" />
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
</html>
but it's not work.
The issue may be with this line:
fullname = request.getParameter("email");
Note that you are assigning the email parameter to the fullname variable.
first what i see is that the Query is wrong. Remove the , after the table alias "a" (here line 2) like this:
"SELECT a.fullname, a.email,"
+ " FROM mainr a"
+ "WHERE a.fullname = ?"
+ "AND a.email = ?");
There is also an issue here:
<td><%= showits.getString("Phone")%></td>
You did not include Phone in the SELECT statement, so it will not exist in the ResultSet.

can not update using JSP

can you help me resolve my problem?I use JSP to update but no action be occurred(insert and delete be OK).For example,I update cname from ASUS to SONY but when click on Update button,cname still be ASUS.
note that cid is auto_increment
Here is update method in DAO
public int updateComputer(Computer com) {
int n = 0;
try {
String sql = "UPDATE Computer SET cname=?, quantity=?, price=?,functions=? where cid=?";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
// Parameters start with 1
preparedStatement.setString(1, com.getCname());
preparedStatement.setInt(2, com.getQuantity());
preparedStatement.setDouble(3, com.getPrice());
preparedStatement.setString(4, com.getFunc());
n = preparedStatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(ComputerDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return n;
}
here is updateComputer.jsp
<%#page import="java.sql.ResultSet"%>
<%#page import="dao.ComputerDAO"%>
<%#page import="entity.Computer"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
ComputerDAO comDAO = new ComputerDAO();
String cid = request.getParameter("cid");
ResultSet rs = comDAO.getData("Select * from Computer where cid=" + Integer.parseInt(cid));
Computer com = new Computer();
if (rs.next()) {
int id = rs.getInt(1);
String cname = rs.getString(2).trim();
int quan = rs.getInt(3);
double price = rs.getDouble(4);
String func = rs.getString(5).trim();
com = new Computer(id, cname, quan, price, func);
}
%>
<form name="form1" method="post" action="ProcessUpdateComputer.jsp">
<table width="400" height="252" border="0" align="center" cellpadding="2" cellspacing="2">
<caption>
<h2>Update Computer</h2>
</caption>
<tr>
<th width="29%" align="left" scope="row">Computer ID</th>
<td width="71%">
<input type="text" name="cid" id="cid" disabled="" value="<%= com.getCid()%>"></td>
</tr>
<tr>
<th width="29%" align="left" scope="row">Computer Name</th>
<td width="71%">
<input type="text" name="cname" id="cname" value="<%=com.getCname()%>"></td>
</tr>
<tr>
<th align="left" scope="row">Quantity</th>
<td>
<input type="text" name="quantity" id="quantity" value="<%=com.getQuantity()%>"></td>
</tr>
<tr>
<th align="left" scope="row">Price</th>
<td>
<input type="text" name="price" id="price" value="<%= com.getPrice()%>"></td>
</tr>
<tr>
<th align="left" scope="row">Functions</th>
<td>
<!--<input type="text" name="functions" id="functions" value="<%=com.getFunc()%>"></td>-->
<textarea name="functions" rows="8" id="functions" value="<%=com.getFunc()%>"></textarea></td>
</tr>
<tr>
<th align="right" scope="row"></th>
<td><input type="submit" name="button" id="button" value="Update">
<input type="hidden" name="service" id="service" value="<%= cid%>"></td>
</tr>
</table>
<p align="center">View Computer List</p>
</form>
</body>
</html>
Here is ProcessUpdateComputer.jsp
<%#page import="entity.Computer"%>
<%#page import="dao.ComputerDAO"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
ComputerDAO dao = new ComputerDAO();
String cname = request.getParameter("cname");
String quan = request.getParameter("quantity");
String price = request.getParameter("price");
String func = request.getParameter("functions");
int uquan = Integer.parseInt(quan);
double uprice = Double.parseDouble(price);
Computer com = new Computer(0, cname, uquan, uprice, func);
int i = dao.updateComputer(com);
if (i > 0) {
out.println("updated");
}
%>
<p>View Computer List</p>
</body>
</html>
Here you're missing the fifth parameter, the cid:
String sql = "UPDATE Computer SET cname=?, quantity=?, price=?,functions=? where cid=?";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
// Parameters start with 1
preparedStatement.setString(1, com.getCname());
preparedStatement.setInt(2, com.getQuantity());
preparedStatement.setDouble(3, com.getPrice());
preparedStatement.setString(4, com.getFunc());
preparedStatement.setString(5, com.getId());
n = preparedStatement.executeUpdate();
Here is not clear what you want to do, are you always trying to update the computer with cid=0?
Computer com = new Computer(0, cname, uquan, uprice, func);
int i = dao.updateComputer(com);
You'll probably want to retrieve the cid from the request, like the other params
String cid = request.getParameter("cid");

I dono what is the error in my RegController . It does not insert Values in to my Mysql database

This is my Register.jsp code. I am creating a student portal information project . When i try to register it accepts the values and also assign it to the variables in the RegController servlet but it is not inserted in to Mysql database .
<%--
Document : Register
Created on : Apr 23, 2014, 11:54:12 PM
Author : hari
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Register Page</title>
</head>
<body>
<form method="post" name="register" action="RegController">
<table>
<tr>
<td>Email</td>
<td><input type="text" name="Username" size="15" placeholder="Enter the Username" required="required"></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" size="15" placeholder="Enter the Name" required="required"></td>
</tr>
<tr>
<td>Father Name</td>
<td><input type="text" name="fathername" size="15" placeholder="Enter the Father Name" required="required"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="number" name="age" size="5" placeholder="Enter Your Age" required="required"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" size="15" placeholder="Enter the Address" required="required"></td>
</tr>
<tr>
<td>Contact</td>
<td><input type="number" name="contact" size="15" placeholder="Enter the Contact" required="required"></td>
</tr>
<tr>
<td>Department</td>
<td><input type="text" name="dept" size="8" placeholder="Enter the Department" required="required"></td>
</tr>
<tr>
<td>Qualification</td>
<td><input type="text" name="qualification" size="15" placeholder="Enter the Qualification" required="required"></td>
</tr>
<tr>
<td>College</td>
<td><input type="text" name="college" size="50" placeholder="Enter the College Name" required="required"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="Password" size="15" placeholder="Enter the Password" required="required"></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Register"></td>
<td>To LoginClick here</td>
</tr>
</table>
</form>
</body>
</html>
This my Servlet Code RegController.java
import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.*;
import static java.lang.System.out;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author hari
*/
#WebServlet(name = "RegController", urlPatterns = {"/RegController"})
public class RegController extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String name=request.getParameter("name");
//out.println("name"+name);
String Username=request.getParameter("Username");
String age=request.getParameter("age");
String fathername=request.getParameter("fathername");
String address=request.getParameter("address");
String phno=request.getParameter("contact");
String dept=request.getParameter("dept");
String qualification=request.getParameter("qualification");
String college=request.getParameter("college");
String Password=request.getParameter("Password");
String DB_url="jdbc:mysql://localhost:3306/MYFIRSTPROJECT";
String JDBC_Driver="com.mysql.jdbc.Driver";
String UserDB="root" ;
String PassDB="";
int i=1;
Connection conn=null;
PreparedStatement pstmt=null;
//Statement stmt=null;
try{
Class.forName("com.mysql.jdbc.Driver");
//out.println("Connection");
conn=DriverManager.getConnection(DB_url,UserDB,PassDB);
String sql="insert into users VALUES(?,?,?,?,?,?,?,?,?,?)";
//stmt=conn.createStatement();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,Username);
//stmt.executeUpdate(sql);
pstmt.setString(2,Password);
pstmt.setString(3,name);
pstmt.setString(4,fathername);
pstmt.setString(5,address);
pstmt.setString(6,age);
pstmt.setString(7,phno);
pstmt.setString(8,dept);
pstmt.setString(9,qualification);
pstmt.setString(10,college);
pstmt.executeUpdate();
pstmt.close();
//conn.close();
}
catch(SQLException se){
se.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
finally{
try{
if(pstmt!=null)
pstmt.close();
}catch(SQLException se){}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){se.printStackTrace();}
}
//if(i<=1){
// out.println("Error"+i+Username);}
//else{
System.out.println("Registered Successfully");
response.sendRedirect("Welcome.jsp");
//}
}
}
Netbeans doesn't show any errors . Can anybody help plzzz....

Categories