如何在JSP中的derby中插入和删除数据库中的值?

时间:2017-05-24 13:19:16

标签: java jsp

历史:history

问题是我无法从数据库中删除客户。我可以创建一个新客户,但是如果我将这些字段留空,它会在数据库中创建一个空记录,但我会创建一个if标准。

client.java:

public class client implements DatabaseConnection{

private static Connection conn = null;

private static void createConnection(){
try {
  conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException ex) {
  Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}
}

private static void closeConnection(){
if (conn != null){
  try {
    conn.close();
  } catch (SQLException ex) {
    Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
  }
}
}

public List clientList(){
    createConnection();
    List list=new ArrayList();
    try {
        Statement stmt=conn.createStatement();
        ResultSet rs=stmt.executeQuery("SELECT * FROM customer");
        while(rs.next()){
            list.add(rs.getString("CNAME"));
            list.add(rs.getString("ADDRESS"));
            list.add(rs.getString("PHONENUMBER"));
        }
        stmt.close();
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
    return list;
}

public void newClient(String name, String address, String phoneNumber) 
throws SQLException{
    PreparedStatement ps = null;
    try {
        createConnection();
        String insert="INSERT INTO CUSTOMER(CNAME,ADDRESS, PHONENUMBER) 
VALUES(?,?,?)";
        ps=conn.prepareStatement(insert);
        ps.setString(1, name);
        ps.setString(2, address);
        ps.setString(3, phoneNumber);
        ps.executeUpdate();
        ps.close();
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
    finally {
        ps.close();
        closeConnection();
    }
}
public void deleteClient(String ID){
    try {
        createConnection();
        String delete="DELETE FROM CUSTOMER WHERE ID=?";
        PreparedStatement ps=conn.prepareStatement(delete);
        ps.setString(1, ID);
        ps.executeUpdate();
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

}

index.jsp:

<jsp:useBean id="client" class="database.client" scope="page" />
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body bgcolor="lightgrey">
    <%
        String ID=request.getParameter("ID");
        String NAME=request.getParameter("CNAME");
        String ADDRESS=request.getParameter("ADDRESS");
        String PHONENUMBER=request.getParameter("PHONENUMBER");
    %>
    <form method="post" action="">
    <table border="0" align="left">
        <th colspan="2" align="center" style="color: brown">Field</th>
        <tr>
            <td>Name:</td>
            <td><input type="text" name="CNAME" style="background-
color:beige"/></td>
        </tr>
        <tr>
            <td>Address?</td>
            <td><input type="text" name="ADDRESS" style="background-
color:beige"/></td>
        </tr>
        <tr>
            <td>PhoneNumber:</td>
            <td><input type="text" name="PHONENUMBER" style="background-
color:beige"/></td>
        </tr>
            <input type="submit" name="OK" onclick="
                <%
               if(NAME!=null && ADDRESS!=null && PHONENUMBER!=null){
                    client.newClient(NAME, ADDRESS, PHONENUMBER);
                }
                %>" value="OK"/>
            <input type="submit" name="Cancel" onclick="
               <%
               //nothing
               %>" value="Cancel"/>
            <input type="submit" name="Delete" onclick="
<%client.deleteClient(ID);%>" value="Delete"/>
    </table>
    <table border="2">
        <th colspan="4" align="center" bgcolor="orange">Clients</th>
        <tr bgcolor="silver" align="center">
            <td>&nbsp;</td>
            <td>Name</td>
            <td>Address</td>
            <td>PhoneNumber</td>
        </tr>
        <%
            List list=client.clientList();
            Iterator it=list.iterator();

            while(it.hasNext()){
                out.print("<tr bgcolor='lightgreen'>");
                out.print("<td>");
                NAME=(String)it.next();
                out.print("<input type='radio' name='ID' value="+NAME+"/>");
                out.print("</td>");
                out.print("<td>");
                out.print(NAME);
                out.print("</td>");
                for (int i = 0; i < 2; i++) {
                    out.print("<td>");
                    out.print(it.next());
                    out.print("</td>");
                }
            out.print("</tr>");

            }
        %>
    </table>
</form>  
</body>
</html>

如果我将字段留空并单击“确定”,则会显示以下错误消息:     引起:org.apache.derby.client.am.SqlException:没有实际连接。

如果没有连接怎么能创建一个空记录?

Severe:   java.lang.NullPointerException at: client.java PreparedStatement ps=conn.prepareStatement(delete);

修改 新错误:     严重:java.sql.SQLDataException:INTEGER的字符串格式无效。

2 个答案:

答案 0 :(得分:0)

您似乎没有在列表中设置ID

while(rs.next()){
        list.add(rs.getString("ID")); // Add this
        list.add(rs.getString("CNAME"));
        list.add(rs.getString("ADDRESS"));
        list.add(rs.getString("PHONENUMBER"));
    }

在列表中没有ID,您将无法从jsp访问相同的内容,并且当您调用delete方法时,它们将不可用。

另一件事是确保ID是字符串而不是int。通常我们将密钥(即此处的ID)保留为整数。

答案 1 :(得分:0)

我从上一个问题中了解到你将ID定义为整数,所以你应该使用setInt而不是setString,试试

public void deleteClient(Integer id){

    try {

        createConnection();
        String delete="DELETE FROM CUSTOMER WHERE ID=?";
        PreparedStatement ps=conn.prepareStatement(delete);
        ps.setInt(1, id);
        ps.executeUpdate();
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        ps.close();
        closeConnection();
    }
}

Id是数据库字段中的一个整数,您定义它是一个主键。

更新1

在index.jsp中使用以下命令将String转换为int,将idNum传递给您的方法。

 Integer idNum = null;
 String id = request.getParameter("ID");
    if(id != null) {
        try {
            System.out.println("String Id value --> "+id.trim());
            idNum = Integer.parseInt(id.trim());
        }
        catch(NumberFormatException ex) {
            ex.printStackTrace();
        }
    }