Monday, June 27, 2016

Java : WebServer Database Connection and retreive data

WebServer Database Connection and retrieve data


Notes:

  1. doPost(..) method is generally used for Insertion /updation / deletion of data , 
  2. doGet(..) is used when the users tries to request for any Read Only data.

Pre -Req :

  1.  Using MySQL as DB Server
  2. Download "MySQL connector J.Jar" driver file and paste it into "Project/WebContent/WEB-INF/lib" folder path.
  3. Add the same file into project build directory.
  4. Download "Apache Commons DbUtils" jar file and paste it into "Project/WebContent/WEB-INF/lib" folder path.
  5. Repeat step 3.

DBHelper method: 
The below method return the results of the query in the form of Query list.


    public List SelectQuery(String sURL,String sUsn,String sPassword,String sQuery){
        ResultSet rs=null;
        MapListHandler rstoList=new MapListHandler();
        Map<String,Object> MapQuery=new HashMap<String,Object>();
        List resList=null;
       
        try {
            Class.forName("com.mysql.jdbc.Driver");   
            Connection connection = DriverManager.getConnection(sURL,sUsn, sPassword);           
            Statement st=(Statement) connection.createStatement();
             rs=st.executeQuery(sQuery);
             resList= rstoList.handle(rs);
             rs.close();
             st.close();
             connection.close();           
               
      }catch(Exception e){
          System.out.println("Failed to make connection!");
          e.printStackTrace();
      }       
        return resList;
    }


 Serverlet :
 Calling Method 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    
        DBHelper DBHelp=new DBHelper();
         PrintWriter out=response.getWriter();
        out.print(DBHelp.SelectQuery(sURL,sUsername,sPassword,"Select * from mydb.login;"));
    }

No comments:

Post a Comment