WebServer Database Connection and retrieve data
Notes:
- doPost(..) method is generally used for Insertion /updation / deletion of data ,
- doGet(..) is used when the users tries to request for any Read Only data.
Pre -Req :
- Using MySQL as DB Server
- Download "MySQL connector J.Jar" driver file and paste it into "Project/WebContent/WEB-INF/lib" folder path.
- Add the same file into project build directory.
- Download "Apache Commons DbUtils" jar file and paste it into "Project/WebContent/WEB-INF/lib" folder path.
- 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