Monday, October 13, 2014

web service with Java DB

http://www.mkyong.com/jdbc/jdbc-preparestatement-example-insert-a-record/

/*
 * To change this template, 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 java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.sql.DataSource;

/**
 *
 * @author Hasangi
 */
@WebService(serviceName = "wsRate")
public class wsRate {
    @Resource(name = "mybank")
    private DataSource mybank;

    /**
     * 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) {
        try {
            //TODO write your implementation code here:
           
            Connection con=mybank.getConnection();
            PreparedStatement psts=con.prepareStatement("select value from rate where id=?");
            psts.setInt(1, 1);
            ResultSet rs= psts.executeQuery();
            rs.next();
            double rate=rs.getDouble(1);
            rs.close();
            con.close();           
            return usd*rate;
           
        } catch (SQLException ex) {
            Logger.getLogger(wsRate.class.getName()).log(Level.SEVERE, null, ex);
             return 0.0;
        }
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "AddRate")
    public String AddRate(@WebParam(name = "id") int id, @WebParam(name = "rate") double rate) {
        try {
            //TODO write your implementation code here:
            String insertTableSQL = "INSERT INTO APP.RATE"
                + "(ID, VALUE) VALUES"
                + "(?,?)";
             Connection conn=mybank.getConnection();
            PreparedStatement pstss=conn.prepareStatement(insertTableSQL);
            pstss.setInt(1, id);
            pstss.setDouble(2,rate);
            pstss.executeUpdate();
           
            return "Insert Sucess";
        } catch (SQLException ex) {
            Logger.getLogger(wsRate.class.getName()).log(Level.SEVERE, null, ex);
             return "Not Insert";
        }
    }
   
   
}

No comments:

Post a Comment