Jsp Tutorial Home

Jsp Home

JSP Resources

Community

Site

JDBC and JSP


This section will explain how do we can use the JDBC code in the JSP page. The below example will get the data from the customer table of the database and display in the HTML table. The Customer table has only one row and has ID and name as columns.


Example:-









<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@page import="java.sql.*;" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

<%

    Connection con = null;

    Statement stmt = null;

    try{

        Class.forName("com.mysql.jdbc.Driver");

        con=DriverManager.getConnection("jdbc:mysql://localhost:3309/test","root","root");

        stmt= con.createStatement();

        ResultSet rs= stmt.executeQuery("select * from Customer");

        out.println("Retreived Data is as follows:-<br>");

        while (rs.next()){

            out.println("ID is "+ rs.getInt("id")+"<br>");



            out.println("Name is "+ rs.getString("name")+"<br>");

        }

    }catch(Exception e){

        e.printStackTrace();

        out.println("Exception Occured");

    }finally{

        if(con != null) con.close();

        if(stmt != null) stmt.close();

    }


%>


</body>

</html>



Output:- The following screen will be displayed when the file is run.


 

                    

Copyright © 2012 VisualBuilder. All rights reserved