Guest User

Untitled

a guest
Dec 17th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. package javaPractice.jdbc;
  2.  
  3. //Import required packages
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.sql.Statement;
  9.  
  10. public class JdbcExample {
  11.  
  12. static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  13. static final String DB_URL = "jdbc:mysql://localhost:3306/cms_crud?useSSL=false";
  14.  
  15. static final String USER = "root";
  16. static final String PASS = "admin1234";
  17.  
  18. public static void main(String[] args) {
  19.  
  20. Connection conn = null;
  21. Statement stmt = null;
  22.  
  23. try {
  24.  
  25. // Register JDBC driver
  26. Class.forName("com.mysql.jdbc.Driver");
  27.  
  28. System.out.println("Connecting to database...");
  29. // Open a connection
  30. conn = DriverManager.getConnection(DB_URL, USER, PASS);
  31.  
  32. // Execute a query
  33. System.out.println("Creating statement...");
  34. stmt = conn.createStatement();
  35. String sql = "SELECT ID, FIRST_NAME, LAST_NAME, EMAIL FROM USER";
  36.  
  37. ResultSet rs = stmt.executeQuery(sql);
  38.  
  39. // Extract data from result set
  40. while (rs.next()) {
  41. // Retrieve by column name
  42. int id = rs.getInt("ID");
  43. String first = rs.getString("FIRST_NAME");
  44. String last = rs.getString("LAST_NAME");
  45. String email = rs.getString("EMAIL");
  46.  
  47. // Display values
  48. System.out.print("ID: " + id);
  49. System.out.print(", First: " + first);
  50. System.out.print(", Last: " + last);
  51. System.out.println(", Email: " + email);
  52. }
  53.  
  54. // Clean-up environment
  55. rs.close();
  56. stmt.close();
  57. conn.close();
  58.  
  59. } catch (SQLException | ClassNotFoundException se) {
  60. // Handle errors for JDBC
  61. se.printStackTrace();
  62. }
  63.  
  64. }
  65.  
  66. }
Add Comment
Please, Sign In to add comment