Guest User

Untitled

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