Advertisement
Guest User

Untitled

a guest
Mar 15th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. import java.io.*;
  2. import javax.servlet.*;
  3. import javax.servlet.annotation.WebServlet;
  4. import javax.servlet.http.*;
  5. import java.sql.*;
  6. @WebServlet("/DatabaseAccess")
  7. public class Databaseaccess extends HttpServlet {
  8.  
  9. private static final long serialVersionUID = 1L;
  10.  
  11. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  12.  
  13. // JDBC driver name and database URL
  14. final String DB_URL_with_SSL = "jdbc:mysql://127.0.0.1:3306/?user=root";
  15.  
  16. // Database credentials
  17. final String USER = "root";
  18. final String PASS = "denise9955";
  19.  
  20. // Set response content type
  21. response.setContentType("text/html");
  22. PrintWriter out = response.getWriter();
  23. String title = "Database Result";
  24.  
  25. String docType = "<!doctype html>\n";
  26.  
  27. out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body>\n" + "<h1>" + title
  28. + "</h1>\n");
  29. try {
  30. // Register JDBC driver
  31. Class.forName("com.mysql.cj.jdbc.Driver");
  32.  
  33. // Open a connection with a try-with-resources: non c'e' bisogno di chiamare la funzione close su conn, verrà chiusa alla fine del body
  34. try (Connection conn = DriverManager.getConnection(DB_URL_with_SSL, USER, PASS)) {
  35. // Execute SQL query
  36. try (Statement stmt = conn.createStatement()) {
  37. String sql;
  38. sql = "SELECT nome, cognome FROM registration where login = 'fsina'";
  39. try (ResultSet rs = stmt.executeQuery(sql)) {
  40. // Extract data from result set
  41. while (rs.next()) {
  42. // Retrieve by column name
  43. String first = rs.getString("nome");
  44. String last = rs.getString("cognome");
  45.  
  46. // Display values
  47. out.println("<h2>Ciao " + first + " ");
  48. out.println(last + "<h2>");
  49. }
  50.  
  51. out.println("</body></html>");
  52.  
  53. }
  54.  
  55. }
  56.  
  57. }
  58.  
  59. } catch (SQLException | ClassNotFoundException e) {
  60. // Handle errors for JDBC
  61. e.printStackTrace();
  62. }
  63. }
  64. }
  65.  
  66.  
  67.  
  68. MI DA' ERRORE SQL, "DATABASE NOT SELECTED"
  69. why?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement