
thanks for web site.
I want change this code to insert data into PostgreSql database using jsp,servlets.
but i getting output "Record has been inserted",
1.no data in the table(sample)
public class ServletUser extends HttpServlet
{
try {
Class.forName("org.postgresql.Driver");
PreparedStatement pst = connection.prepareStatement("INSERT into sample VALUES(?,?)");
pst.setString(1,username);
pst.setString(2,pass);
int numRowsChanged = pst.executeUpdate();
if(numRowsChanged!=0){
out.println("<br>Record has been inserted");
}
else{
out.println("failed to insert the data");
}
pst.close();
}
catch(ClassNotFoundException e){
out.println("Couldn't load database driver: " + e.getMessage());
}
catch(SQLException e){
out.println("SQLException caught: " + e.getMessage());
}
catch (Exception e){
out.println(e);
}
finally {
// Always close the database connection.
try {
if (connection != null) connection.close();
}
catch (SQLException ignored){
out.println(ignored);
}
}
}
}
//AddForm.jsp
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Add Data To DataBase</title>
</head>
<body>
<form name="TestForm" method="post" action="/ServletUser">
<label>
<label>Emp_Id</label>
<input type="text" name="empid" />
</label>
<label>Emp_Name
<input type="text" name="ename" />
</label>
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>
AddDataBase</display-name>
<servlet>
<servlet-name>ServletUser</servlet-name>
<servlet-class>data.ServletUser</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletUser</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>AddForm.jsp</welcome-file>
</welcome-file-list>
</web-app>
//Database name: postgres
CREATE TABLE sample
(
username character(20),
pass character(15)
)
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.