大家好,我在 JSF 中有一个数据表,它显示了我的数据库表的所有内容,它显示得很好,我还有一个删除功能,可以成功地从数据库中删除并更新数据表,但是当我尝试更新数据库我得到错误
java.lang.IllegalArgumentException: Cannot convert richard.test.User@129d62a7 of type class richard.test.User to long
下面是我一直用来删除数据库中运行良好的行的代码:
public void delete(long userID) {
PreparedStatement ps = null;
Connection con = null;
if (userID != 0) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
String sql = "DELETE FROM user1 WHERE userId=" + userID;
ps = con.prepareStatement(sql);
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("Row deleted successfully");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
我只是想编辑上面的代码,所以它会更新记录而不是删除它们,所以我编辑它看起来像:
public void editData(long userID) {
PreparedStatement ps = null;
Connection con = null;
if (userID != 0) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
String sql = "UPDATE user1 set name = '"+name+"', email = '"+ email +"', address = '"+address+"' WHERE userId=" + userID;
ps = con.prepareStatement(sql);
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("Row updated successfully");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
xhmtl 是:
<p:dataTable id="dataTable" var="u" value="#{userBean.getUserList()}"
paginator="true" rows="10"
editable="true"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15">
<p:column>
<f:facet name="header">
User ID
</f:facet>
#{u.userID}
</p:column>
<p:column>
<f:facet name="header">
Name
</f:facet>
#{u.name}
</p:column>
<p:column>
<f:facet name="header">
Email
</f:facet>
#{u.email}
</p:column>
<p:column>
<f:facet name="header">
Address
</f:facet>
#{u.address}
</p:column>
<p:column>
<f:facet name="header">
Created Date
</f:facet>
#{u.created_date}
</p:column>
<p:column>
<f:facet name="header">
Delete
</f:facet>
<h:commandButton value="Delete" action="#{user.delete(u.userID)}" />
</p:column>
<p:column>
<f:facet name="header">
Delete
</f:facet>
<h:commandButton value="Edit" action="#{user.editData(u)}" />
</p:column>
目前,当您按下编辑按钮时,它只会使用相同的值更新它,因为我还没有设法使数据表可与数据库一起编辑,我已经看到了一些带有数组列表的示例,其中数据表获取它来自但从来没有数据库的值,所以如果您对此也有任何建议,那就太好了
谢谢