Monday, October 13, 2014

Web service with DB java



Web service with DB java
wsRate.java class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pac;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.annotation.Resource;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.sql.DataSource;

/**
 *
 * @author Madhura
 */
@WebService(serviceName = "wsRate")
public class wsRate {

    @Resource(name = "mybanck")
    private DataSource mybanck;

    /**
     * This is a sample web service operation
     */
    @WebMethod(operationName = "hello")
    public String hello(@WebParam(name = "name") String txt) {
        return "Hello " + txt + " !";
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "exchange")
    public double exchange(@WebParam(name = "usd") double usd) {
        //TODO write your implementation code here:
        try {

            Connection con = mybanck.getConnection();
            PreparedStatement pstmt = con.prepareStatement("select value from rate where id=?");
            // preparedStatement("select value from rate where id=?");
            pstmt.setInt(1, 1);
            ResultSet rs = pstmt.executeQuery();
            rs.next();
            double rate = rs.getDouble(1);
            rs.close();
            con.close();
            return usd * rate;

        } catch (Exception ex) {
            System.err.println(ex.getMessage());
            return 0.0;
        }

    }
}

No comments:

Post a Comment