Select data from a SQL database 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.

If you have not yet created a package, in the left panel of Eclipse, expand the Java Resources folder, right click on the src folder, and select New > Package. Give the package a name, such as com.main.servlet and select Finish. Right click on the package and select New > Servlet. Give the servlet a name, such as myServlet, and select Finish.

Import the following items.

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;

 

In the doGet method section of the markup, add the following.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
	
  try {
    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())
    {
      String columnName = rs.getString("colum_name");
      out.println(columnName);
    }
    st.close();
 
    } catch (Exception e2) {
      System.out.println(e2);
    }
    out.close();
}

 

Add the following to your web.xml file.

    <servlet>
        <servlet-name>myServlet</servlet-name>
        <servlet-class>com.jwt.servlet.myServlet</servlet-class>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>myServlet</servlet-name>
        <url-pattern>/myservlet</url-pattern>
    </servlet-mapping>

 

Run the application in Eclipse, or export the WAR and run the application on an application server. Now, when navigating to www.example.com/app_name/myServlet, data from SQL should be displayed.



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