I am trying to insert data into a database named mtdb , table userDB I am writing my web app in JSF, I am able to render the primeface elements included in my code and when I click submit it is not inserting anything into the database can you please help me out
my XHTML page is
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Simple Web App</title>
</h:head>
<h:body>
<h:form>
<p:outputLabel>Name:</p:outputLabel> <p:inputText id="nmn" value="#{sgbean.nmn}" />
<p:outputLabel>Password:</p:outputLabel> <p:inputText id="pwd" value="#{sgbean.pwd}" />
<p:commandButton id="btn" value="Submit" type="Submit" action="sgbean.add" />
</h:form>
</h:body>
</html>
Managed Bean Code:
package jsfappTest;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;
@SuppressWarnings("unused")
@ManagedBean(name="sgbean")
@RequestScoped
public class BeanGs {
PreparedStatement ps = null;
Connection con = null;
int i=0;
private String nmn;
private String pwd;
private String msg;
public String getNmn() {
return nmn;
}
public void setNmn(String nmn) {
this.nmn = nmn;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getMsg() {
return msg; }
public void add(){
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mtdb", "root", " ");
String sql = "INSERT INTO userDB(name,pwd) VALUES(?,?)";
ps= con.prepareStatement(sql);
ps.setString(1, nmn);
ps.setString(2, pwd);
i = ps.executeUpdate();
System.out.println("Data Added Successfully");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
try
{
con.close();
ps.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
I updated my managedBean "try" and "catch" blocks shown in the above to identify the error
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mtdb", "root", "");
con.setAutoCommit(false);
Statement stmt = con.createStatement();
String sql = "INSERT INTO userdb(name,pwd) VALUES('"+nmn+"','"+pwd+"')";
stmt.executeUpdate(sql);
con.commit();
}
Catch block is updated as
catch(Exception e)
{
throw new FacesException(e);
}
Then i included the "mysql-connector-java-5.0.8-bin.jar" file under lib folder and it worked absolutely fine Thanks for all the help finally i am able to figure it out using the hints provided