Display data from SQL is a JSP page in Eclipse

Home > Search
  by

This assumes you have created your first dynamic web project in Eclipse and you can can connect to a database. The easiest way to get started is to write all of your code in a JSP page, such as index.jsp. First, pace the following lines at the very top of your JSP page.

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

 

Then, place the following markup in the <body> section of your JSP page.

<%
String column1=request.getParameter("column1");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://hostname:3306/database_name","username","password");
String query = "select * from table_name";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next())
{
%>

<p><%=rs.getString("column1")%></p>

<%
}
st.close();	
%>

 

Running your JSP page in Eclipse, or deploying your app to an application server (Tomcat, WebSphere), should display records in your dabase.

 


Java SQL class

There are many reasons why the prior example is poor programming. For example, if your app grows to have 20 JSP pages, where each JSP page has the prior markup, when you change your SQL password, you would need to update 20 different JSP pages. For this reason, it makes much more sense to place your database connection into a Java class, and to then call the class in your JSP page. To accompish this, first start be creating a dedicated class to connect to your database. For example, let's say you create a class called DbConnect, and this class is in your com.main.servlet. To be able to use the class in your JSP page, add the following to the very top of your JSP page.

<%@page import="com.main.servlet.DbConnect"%>

 

Now, you can remove the markup that was used to create the connection to the database, and add the first two lines below, to use the DbConnect in your JSP page.

<%
DbConnect db = new DbConnect();
Connection conn = db.getConnection();

String column1=request.getParameter("column1");
String query = "select * from table_name";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next())
{
%>

<p><%=rs.getString("column1")%></p>

<%
}
st.close();	
%>

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments