我正在尝试将数据插入名为mtdb的数据库,表userDB 我在jsf中编写我的网络应用程序,我能够渲染我的代码中包含的primeface元素,当我点击提交它没有插入任何数据库,你可以帮助我
我的xhtml页面是
<?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>
托管Bean代码:
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();
}
}
}
}
答案 0 :(得分:0)
p:commandbutton上的action属性应该是action =&#34;#{sgbean.add()}
答案 1 :(得分:0)
我更新了上面显示的managedBean“try”和“catch”块以识别错误
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块更新为
catch(Exception e)
{
throw new FacesException(e);
}
然后我在lib文件夹下包含了“mysql-connector-java-5.0.8-bin.jar”文件并且它工作得非常好感谢所有的帮助,最后我能够使用提供的提示弄清楚