How can I insert value to a database to derby in JSP?

烂漫一生 提交于 2019-12-02 05:18:30

Your preparedStatement index should start from 1, not from 2, so try as

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

PreparedStatement or Connection close methods should be in the finally part of try catch finally block.

Similar to the closeConnection() method, you can create another method for closing preparedStatement and call that in the finally block.

Update 1

If you are capturing Id in Java, then try as

public void newClient(Integer id, String name, String address, String phoneNumber){
    PreparedStatement ps = null;
    try {
        createConnection();
        String insert="INSERT INTO CUSTOMER(CNAME,ADDRESS, PHONENUMBER) VALUES(?,?,?)";
        ps=conn.prepareStatement(insert);
        ps.setInt(1, id)
        ps.setString(2, name);
        ps.setString(3, address);
        ps.setString(4, phoneNumber);
        ps.executeUpdate();
    } catch (Exception ex)  {
        ex.printStackTrace();
    } finally  {
        ps.close();
        closeConnection();
    }
}    

And in the JSP, modify as

if(ID!=null && NAME!=null && ADDRESS!=null && PHONENUMBER!=null){
                    client.newClient(ID, NAME, ADDRESS, PHONENUMBER);
                }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!