簡體   English   中英

使用REST Web服務更新數據庫行

[英]Updating database row with REST web service

我需要一些幫助,我有一個RESTful Web服務,可以插入用戶選擇的用戶並更新用戶點,但事實是我無法使更新部分正常工作,所以這是我的DBConnection類的代碼:

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;

    }
}

現在是我的網絡服務電話:

    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;
            }


}

事實是,輸出告訴我它正在達到DBCOnnection類中的updateProcedure,但是當我查看數據庫時,沒有任何更新,因此我去了一個主類並運行以下命令:

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"));

    }

}

並完成了我想要的工作,即更新了用戶點,但是Web服務卻沒有。 為什么?

    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;
            }


}

我不知道為什么我確實調用了該方法才能解決問題,而如果其他方法中的updatePoints無法解決問題,那對我有用,因此如果有人遇到同樣的問題,請來這里回答。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM