Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. import java.sql.*;
  2.  
  3. public class JDBCExample {
  4. // JDBC driver name and database URL
  5. static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  6. static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
  7.  
  8. // Database credentials
  9. static final String USER = "username";
  10. static final String PASS = "password";
  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.  
  19. //STEP 3: Open a connection
  20. System.out.println("Connecting to a selected database...");
  21. conn = DriverManager.getConnection(DB_URL, USER, PASS);
  22. System.out.println("Connected database successfully...");
  23.  
  24. //STEP 4: Execute a query
  25. System.out.println("Creating statement...");
  26. stmt = conn.createStatement();
  27.  
  28. String sql = "SELECT id, first, last, age FROM Registration";
  29. ResultSet rs = stmt.executeQuery(sql);
  30. //STEP 5: Extract data from result set
  31. while(rs.next()){
  32. //Retrieve by column name
  33. int id = rs.getInt("id");
  34. int age = rs.getInt("age");
  35. String first = rs.getString("first");
  36. String last = rs.getString("last");
  37.  
  38. //Display values
  39. System.out.print("ID: " + id);
  40. System.out.print(", Age: " + age);
  41. System.out.print(", First: " + first);
  42. System.out.println(", Last: " + last);
  43. }
  44. rs.close();
  45. }catch(SQLException se){
  46. //Handle errors for JDBC
  47. se.printStackTrace();
  48. }catch(Exception e){
  49. //Handle errors for Class.forName
  50. e.printStackTrace();
  51. }finally{
  52. //finally block used to close resources
  53. try{
  54. if(stmt!=null)
  55. conn.close();
  56. }catch(SQLException se){
  57. }// do nothing
  58. try{
  59. if(conn!=null)
  60. conn.close();
  61. }catch(SQLException se){
  62. se.printStackTrace();
  63. }//end finally try
  64. }//end try
  65. System.out.println("Goodbye!");
  66. }//end main
  67. }//end JDBCExample
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement