In this program, I have to set already existing va

2019-09-20 01:06发布

问题:

           public void UpdateCustomer(Customer customer) throws CustomerHomeException, ClassNotFoundException{

    try {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        String url = "jdbc:odbc:Mydb";
        String user = "user1";
        String password = "password";
        Connection con = DriverManager.getConnection(url,user,password);
        PreparedStatement smt= con.prepareStatement("update customer SET ssn = ? customer_name = ? where ssn = ?");
        if(getCustomer.equals(customer.getSocialSecurityNumber()))
        smt.setString(1,customer.getSocialSecurityNumber());
        smt.setString(2, customer.getName());
        smt.setString(3, customer.);
        smt.executeUpdate();
        smt.close();
        con.close();
}
    catch (SQLException e){
        throw new CustomerHomeException("Failed to create CustomerHome", e);
    }
}

but I am confused how can i retrieve value for existing ssn. Also I have a method getCustomers to retrieve a particular customer separately. Will that help

回答1:

I recommend that you revisit your database model. You are using SSN as a primary-key (based on you WHERE clause), but then you're trying to update it. It is EXTREMELY poor practice to update primary keys (ref: https://stackoverflow.com/a/3838649/2065845). If you introduce some other key value (an auto-incrementing ID perhaps?), then you'll be able to modify your update statement's WHERE clause to use that ID, and the fact that you no longer have the old SSN becomes unimportant.

Barring that, you'll either need to modify your method signature to include the old SSN, or you'll need to execute a SELECT with some other value to get the old SSN (though, if you can do that, I have to wonder why you don't just use that in the WHERE clause of your UPDATE statement).



标签: java jdbc