Guest User

ABC

a guest
Feb 26th, 2020
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. package conn;
  2.  
  3. import java.sql.*;
  4. public class JDBCExample {
  5. // JDBC driver name and database URL
  6. static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  7. static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
  8. // Database credentials
  9. static final String USER = "root";
  10. static final String PASS = "mysql";
  11.  
  12. public static void main(String[] args) {
  13. Connection conn = null;
  14. Statement stmt = null;
  15. try{
  16. //STEP 2: Register JDBC driver
  17. Class.forName("com.mysql.jdbc.Driver");
  18. //STEP 3: Open a connection
  19. System.out.println("Connecting to database...");
  20. conn = DriverManager.getConnection(DB_URL, USER, PASS);
  21. //STEP 4: Execute a query
  22.  
  23. String sql = "SELECT * FROM register";
  24. stmt = conn.createStatement();
  25. ResultSet rs = stmt.executeQuery(sql);
  26. //STEP 5: Extract data from result set
  27. while(rs.next()){
  28. //Retrieve by column name
  29.  
  30. String first = rs.getString("username");
  31. String last = rs.getString("password");
  32. //Display values
  33.  
  34. System.out.print(", First: " + first);
  35. System.out.println(", Last: " + last);
  36. }
  37. rs.close();
  38.  
  39.  
  40.  
  41. }catch(Exception e){
  42. //Handle errors for Class.forName
  43. e.printStackTrace();
  44. }finally{
  45. //STEP 5: finally block used to close resources
  46. try{
  47. if(stmt!=null)
  48. stmt.close();
  49. }catch(SQLException se2){
  50. }// nothing we can do
  51. try{
  52. if(conn!=null)
  53. conn.close();
  54. }catch(SQLException se){
  55. se.printStackTrace();
  56. }//end finally try
  57. }//end try
  58. System.out.println("Goodbye!");
  59. }//end main
  60. }//end JDBCExample
Add Comment
Please, Sign In to add comment