Monday, December 10, 2018

Insert update delete data in web service using java and mysql. [with source code] - part 01


In this tutorial I show you how data insert update and delete in web service. Here I use java and mysql database. watching this tutorial you can get better idea about web service. Here include video tutorial and source codes.




Database connection file


package syntech;

import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import javax.ejb.Stateless;
import javax.swing.JOptionPane;

/**
 *
 * @author Ruwan from SynTech
 */
@Stateless
public class DBConnect {

 
    public static Connection serverConnect()
    {
        Connection con=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/webtest?","root","");
       
         
        } catch (Exception e) {
            System.out.println("inter.DBConnect.connect()");
            JOptionPane.showConfirmDialog(null,e);
        }
       return con;
    }
 
}

Web service file

package syntech;

import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;

/**
 *
 * @author Ruwan from SynTech
 */
@WebService(serviceName = "WebServer")
public class WebServer {
    Connection con = DBConnect.serverConnect();

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

         try {
           String sq="INSERT INTO `test`(`id`, `name`) VALUES ('"+id+"','"+name+"')";
             PreparedStatement pst=con.prepareStatement(sq);
           pst.execute();
        //   update();
        } catch (Exception e) {
          // JOptionPane.showMessageDialog(rootPane, e);
        }
     
    }
 
 
     @WebMethod(operationName = "update")
    public void update(@WebParam(name = "id") String id, @WebParam(name = "name") String name ) {

        try {
              String squpdate = "UPDATE test SET name='"+name+"' where id='"+id+"'";
            PreparedStatement pst=con.prepareStatement(squpdate);
            pst.execute();
        } catch (Exception e) {
        }
       
       
     
    }
 
        @WebMethod(operationName = "delete")
    public void delete(@WebParam(name = "id") String id) {

        try {
         
            String sql="DELETE FROM test where id='"+ id +"'";
               PreparedStatement pst=con.prepareStatement(sql);
                pst.execute();
         
        } catch (Exception e) {
        }
       
       
     
    }
 
 
 
 
}

No comments:

Post a Comment