简体   繁体   中英

Updating database row with REST web service

i need some help, i have a RESTful web service that does insert of users select of users and update user points, the thing is that I can´t make the updating part to work, so here´s the code for my DBConnection Class:

package com.prgguru.jersey;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;






public class DBConnection {

    @SuppressWarnings("finally")
    public static Connection createConnection() throws Exception {
        Connection con = null;
        try {
            Class.forName(Constants.dbClass);
            con = DriverManager.getConnection(Constants.dbUrl, Constants.dbUser, Constants.dbPwd);
        } catch (Exception e) {
            throw e;
        } finally {
            return con;
        }
    }

    public static boolean InsertProcedure(String name, String idDevice) throws SQLException{
        boolean procedureStatus = false;
        Connection dbConn = null;
        CallableStatement call = null;
        try {
            try {
                dbConn = DBConnection.createConnection();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            call = dbConn.prepareCall("{call Register(?,?)}");
            call.setString(1, name);
            call.setString(2, idDevice);
            call.execute();
            call.close();
            procedureStatus=true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (dbConn != null) {
                dbConn.close();
        }
        }
        return procedureStatus;
    }

    public static String selectUser(String name, String idDevice) throws SQLException{
        String user="";
        int points=0;
        String compUser="";
        Connection dbConn = null;
        String query = "SELECT name, points FROM abcsoftdb.user where(name ='"+name+"' and device_iddevice='"+idDevice+"');";
        try {
            try {
                dbConn = DBConnection.createConnection();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Statement stat = dbConn.createStatement();
            ResultSet rst = stat.executeQuery(query);
            while(rst.next()){
                user = rst.getString("name");
                points = rst.getInt("points");
            }
            compUser = user + " "+ points;
            rst.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            dbConn.close();
        }   

        return compUser;

    }

    public static boolean pointsProcedure(String device, String name, int points) throws SQLException{
        boolean pointsStatus = false;
        Connection dbConn = null;
        CallableStatement call = null;
        System.out.println(points);
        try {
            try {
                dbConn = DBConnection.createConnection();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            call = dbConn.prepareCall("{call Points(?,?,?)}");
            call.setString(1, device);
            call.setString(2, name);
            call.setInt(3, points);
            call.execute();
            System.out.println(points);
            System.out.println("lo hice");
            call.close();
            pointsStatus=true;

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            dbConn.close();
        }
        return pointsStatus;
    }

    public static boolean insertIdDevice(String idDevice, String uniqueDevice) throws SQLException{
        boolean insertStatus = false;
        Connection dbConn = null;
        String query = "INSERT into abcsoftdb.device(iddevice, uniquedevice) values(?,?)";
        try {
            try {
                dbConn = DBConnection.createConnection();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            PreparedStatement stmt = dbConn.prepareStatement(query);
            stmt.setString(1,idDevice);
            stmt.setString(2,uniqueDevice);
            stmt.executeUpdate();
            stmt.close();
            insertStatus= true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (dbConn != null) {
                dbConn.close();
            }
        }
        return insertStatus;

    }

    public static String selectUniqueDevice(String uniqueDevice) throws SQLException{
        String id="";
        Connection dbConn = null;
        String query = "SELECT iddevice from abcsoftdb.device where uniquedevice='"+uniqueDevice +"'";
        try {
            try {
                dbConn = DBConnection.createConnection();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Statement stat = dbConn.createStatement();
            ResultSet rst = stat.executeQuery(query);
            rst.next();
            id = rst.getString("iddevice");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (dbConn != null) {
                dbConn.close();
            }
        }

        System.out.print(id);
        return id;

    }
}

now heres my web service call:

    package com.prgguru.jersey;

import java.sql.SQLException;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

//Path: http://localhost/<appln-folder-name>/register
@Path("/updater")
public class PointsUpdater {

    // HTTP Get Method
            @GET 
            // Path: http://localhost/<appln-folder-name>/register/doregister
            @Path("/doupdate")  
            // Produces JSON as response
            @Produces(MediaType.APPLICATION_JSON) 
            // Query parameters are parameters: http://localhost/<appln-folder-name>/updater/doupdate?device=pqrs&name=ertrt=0&points=points
            public String doUpdate(@QueryParam("device") String device, @QueryParam("name") String name, @QueryParam("points") int points) throws SQLException{
                String response="";
                System.out.print(points);
                int retCode = updatePoints(device,name,points);
                if(retCode == 0){
                    response = Utitlity.constructJSON("updater",true,name,device);
                }else if(retCode == 1){
                    response = Utitlity.constructJSON("updater",false, "You are already registered");
                }else if(retCode == 2){
                    response = Utitlity.constructJSON("updater",false, "Special Characters are not allowed in Username and Password");
                }else if(retCode == 3){
                    response = Utitlity.constructJSON("updater",false, "Error occured");
                }
                return response;
            }

            private int updatePoints(String name, String idDevice,int points){
                System.out.println("Inside checkCredentials");
                int result = 3;
                if(Utitlity.isNotNull(name)){
                    try {
                        if(DBConnection.pointsProcedure(idDevice,name,points)){
                            System.out.println("updating points if");
                            System.out.println(points);
                            result = 0;
                        }
                    } catch(SQLException sqle){
                        System.out.println("RegisterUSer catch sqle");
                        //When Primary key violation occurs that means user is already registered
                        if(sqle.getErrorCode() == 1062){
                            result = 1;
                        } 
                        //When special characters are used in name,username or password
                        else if(sqle.getErrorCode() == 1064){
                            System.out.println(sqle.getErrorCode());
                            result = 2;
                        }
                    }
                    catch (Exception e) {
                        // TODO Auto-generated catch block
                        System.out.println("Inside checkCredentials catch e ");
                        result = 3;
                    }
                }else{
                    System.out.println("Inside checkCredentials else");
                    result = 3;
                }
                return result;
            }


}

the thing is that the output tells me that it is reaching the updateProcedure in the DBCOnnection class, but when i look into the database there is nothing updated, so i went a do a main class an run the following:

package com.prgguru.jersey;

import java.sql.SQLException;

public class PruebasLocales {

    public static void main(String[] args) throws SQLException {
        // TODO Auto-generated method stub

        DBConnection con = new DBConnection();
        //System.out.print(con.InsertProcedure("pruebaint","352106050398576")) ;
        System.out.print(con.pointsProcedure("12345","mai",200));
        //System.out.print(DBConnection.selectUser("pruebaint","352106050398576"));

    }

}

and the that does what i want to, and that is to update user points, But the web service does not. Why?

    package com.prgguru.jersey;

import java.sql.SQLException;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

//Path: http://localhost/<appln-folder-name>/register
@Path("/updater")
public class PointsUpdater {

    // HTTP Get Method
            @GET 
            // Path: http://localhost/<appln-folder-name>/register/doregister
            @Path("/doupdate")  
            // Produces JSON as response
            @Produces(MediaType.APPLICATION_JSON) 
            // Query parameters are parameters: http://localhost/<appln-folder-name>/updater/doupdate?device=pqrs&name=ertrt=0&points=points
            public String doUpdate(@QueryParam("device") String device, @QueryParam("name") String name, @QueryParam("points") int points) throws SQLException{
                String response="";
                System.out.print(points);
                int retCode = updatePoints(device,name,points);
                System.out.print(DBConnection.pointsProcedure(device,name,points));
                if(retCode == 0){
                    response = Utitlity.constructJSON("updater",true,name,device);
                }else if(retCode == 1){
                    response = Utitlity.constructJSON("updater",false, "You are already registered");
                }else if(retCode == 2){
                    response = Utitlity.constructJSON("updater",false, "Special Characters are not allowed in Username and Password");
                }else if(retCode == 3){
                    response = Utitlity.constructJSON("updater",false, "Error occured");
                }
                return response;
            }

            private int updatePoints(String name, String idDevice,int points){
                System.out.println("Inside checkCredentials");
                int result = 3;
                if(Utitlity.isNotNull(name)){
                    try {
                        if(DBConnection.pointsProcedure(idDevice,name,points)){
                            System.out.println("updating points if");
                            System.out.println(points);
                            result = 0;
                        }
                    } catch(SQLException sqle){
                        System.out.println("RegisterUSer catch sqle");
                        //When Primary key violation occurs that means user is already registered
                        if(sqle.getErrorCode() == 1062){
                            result = 1;
                        } 
                        //When special characters are used in name,username or password
                        else if(sqle.getErrorCode() == 1064){
                            System.out.println(sqle.getErrorCode());
                            result = 2;
                        }
                    }
                    catch (Exception e) {
                        // TODO Auto-generated catch block
                        System.out.println("Inside checkCredentials catch e ");
                        result = 3;
                    }
                }else{
                    System.out.println("Inside checkCredentials else");
                    result = 3;
                }
                return result;
            }


}

I don´t know why bu the sout that i did calling the method does the trick and the if in the other method updatePoints does not, that works for me, so heres the answers if anyone has the same issue.

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