我正在尝试将数据插入名为 mtdb 的数据库,表 userDB 我正在用 JSF 编写我的 Web 应用程序,我能够呈现我的代码中包含的 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();
}
}
}
}
最佳答案
我更新了上面显示的 managedBean“try”和“catch” block 以识别错误
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 更新为
catch(Exception e)
{
throw new FacesException(e);
}
然后我将“mysql-connector-java-5.0.8-bin.jar”文件包含在 lib 文件夹下,它工作得非常好感谢所有的帮助,最终我能够使用提供的提示弄清楚
关于mysql - 无法在jsf应用程序中将数据插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30506309/