Advertisement
Guest User

Untitled

a guest
Feb 28th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | None | 0 0
  1. package pap1;
  2.  
  3.  
  4. import java.io.IOException;
  5. import java.io.PrintWriter;
  6.  
  7. import javax.servlet.ServletException;
  8. import javax.servlet.annotation.WebServlet;
  9. import javax.servlet.http.HttpServlet;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import java.sql.*;
  13.  
  14. @WebServlet("/Pap")
  15. public class Pap extends HttpServlet {
  16.      
  17.    
  18.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  19.         Connection con = null;
  20.         try {
  21.             Class.forName("com.mysql.jdbc.Driver").newInstance();
  22.             con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "");
  23.                 if (!con.isClosed())
  24.                     System.out.println("Successfully connected to MySQL server...");
  25.                
  26.                  // if you only need a few columns, specify them by name instead of using "*"
  27.                   String query = "SELECT * FROM persons";
  28.  
  29.                   // create the java statement
  30.                   Statement st = con.createStatement();
  31.                  
  32.                   // execute the query, and get a java resultset
  33.                   ResultSet rs = st.executeQuery(query);
  34.                  
  35.                   while (rs.next())
  36.                   {
  37.                     int id = rs.getInt("id");
  38.                     String firstName = rs.getString("name");
  39.                     String age = rs.getString("age");
  40.                    
  41.                    
  42.                     // print the results
  43.                     System.out.format("%s, %s, %s\n", id, firstName, age);
  44.                   }
  45.                   st.close();
  46.                  
  47.         } catch(Exception e) {
  48.                 System.err.println("Exception: " + e.getMessage());
  49.         } finally {
  50.         try {
  51.                 if (con != null)
  52.                     con.close();
  53.         } catch(SQLException e) {}
  54.         }
  55.        
  56.        
  57.     }
  58.    
  59.    
  60.  
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement