简体   繁体   中英

How to update records in table?

I have 2 table users and user_roles as follow

CREATE TABLE IF NOT EXISTS users ( 
 username char(50) NOT NULL, 
 password char(100) NOT NULL,
 PRIMARY KEY (username)
);
INSERT INTO users values ("root","abc"); 

CREATE TABLE IF NOT EXISTS user_roles ( 
 username char(50) NOT NULL, 
 role_name char(50) NOT NULL,
 FOREIGN KEY (username) REFERENCES users(username) 
  ON UPDATE CASCADE
  ON DELETE CASCADE
); 

INSERT INTO user_roles values ("root","admin");
INSERT INTO user_roles values ("root","role1");
INSERT INTO user_roles values ("root","role2");
INSERT INTO user_roles values ("root","role3");
INSERT INTO user_roles values ("root","role4");

and here is html form to update user roles

  <td>Roles :</td>
     <td>
       <select id="role" name="role" multiple>
         <option value="role1" <%= role1== true ? "selected" : ""%>>role1</option>                                          
         <option value="role2" <%= role2== true ? "selected" : ""%> >role2</option>                                                               
         <option value="role3" <%= role3== true ? "selected" : ""%> >role3</option>
         <option value="role4" <%= recap == true ? "selected" : ""%> >role4</option>
     </td>
 <td> 

and here is servlet code which update users roles in user_roles table but its not working ?

  if (request.getParameterMap().containsKey("roles")) {
        String roleList = request.getParameter("roles");
        String[] role = splitRoles(roleList);

       for (int i = 0; i < role.length; i++) {
              String currentRole = role[i];
                  int editedrole = dao.editUserRoles(currentRole, username);
           }
  }

DAO method ( Updated )

   public int editUserRoles(String roleName,String username) {
    int done = 0 ;
    boolean hasRole = false; // checking whether records with roleName and username exits or not 
    if (connection != null) {
        try {
                System.out.println("Connected to Database updating role");
                String sql1 = "SELECT * FROM user_roles WHERE username = \"" + username + "\" AND role_name = \"" + roleName + "\" ";
                Statement stmt = connection.createStatement();
                ResultSet resultset = stmt.executeQuery(sql1);
                 while(resultset.next()){
                     hasRole = true;
                 } 

                if(hasRole){   // if record exist then only update it
                String sql2 = "UPDATE user_roles SET role_name = ? WHERE username = ? ";
                PreparedStatement ps2 = connection.prepareStatement(sql2);
                ps2.setString(1, roleName);
                ps2.setString(2,username);
                done = ps2.executeUpdate();
                }
                else{  // else add new 
                    addUserRoles(username,roleName);
                }
        }
        catch(Exception e){
            System.out.println("Exception :"+e.getMessage());
        }
    }
    else {
        System.out.println("Not able to connect to database");
    }
    return done;
}

You have not initialized the username variable and passing it in function so the username is null and query output is nothing. before calling editUserRoles() you have to provide the username then you will get the result. i Have tried it will work fine.

I have solved my problem to avoid duplicate records in table,just made changes in servlet code

       if (action.equalsIgnoreCase("edit")) {        
          String username = request.getParameter("username").trim();
          if (request.getParameterMap().containsKey("roles")) {
                        String roleList = request.getParameter("roles").trim();
                        String[] role = splitRoles(roleList);
                        dao.deleteRoles(username); // first delete roles                                                  
                       for(int i = 0;i<role.length;i++){
                           String currentRole = role[i];  
                           dao.addUserRoles(username,currentRole); // then add roles
                       }
          }

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM