Created
March 11, 2019 21:33
-
-
Save dante-byte/9095073d7a88d38f1aa34377dd262bcd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.luv2code.web.jdbc; | |
import java.io.IOException; | |
import java.io.PrintWriter; | |
import java.sql.Connection; | |
import java.sql.ResultSet; | |
import java.sql.Statement; | |
import javax.sql.DataSource; | |
import javax.annotation.Resource; | |
import javax.servlet.ServletException; | |
import javax.servlet.annotation.WebServlet; | |
import javax.servlet.http.HttpServlet; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletResponse; | |
//import com.mysql.jdbc.Connection; | |
/** | |
* Servlet implementation class TestServlet | |
*/ | |
@WebServlet("/TestServlet") | |
public class TestServlet extends HttpServlet { | |
private static final long serialVersionUID = 1L; | |
// step 1 devine datasource/connection pool for resources injections | |
@Resource(name="jdbc/web_student_tracker") // exact name as defined in context.sml | |
private DataSource dataSource; | |
/** | |
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) | |
*/ | |
protected void doGet(HttpServletRequest request, HttpServletResponse response) | |
throws ServletException, IOException { | |
// step 1: set up the printwriter used to send data to the browser | |
PrintWriter out = response.getWriter(); | |
response.setContentType("text/plain"); | |
Connection myConn = null; | |
Statement myStmt = null; | |
ResultSet myRs = null; | |
try { | |
// data source is the same as connection pool | |
myConn = dataSource.getConnection(); | |
// step 3: create a SQL STATEMENT | |
String sql = "select * from student"; | |
myStmt = myConn.createStatement(); | |
// STEP 4: EXCUTE SQL QUERY | |
myRs = myStmt.executeQuery(sql); | |
// STEP 5: PROCESS THE RESULT SET | |
while (myRs.next()) { | |
String email = myRs.getString("email"); | |
out.println(email); | |
} | |
} catch (Exception exc) { | |
exc.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment