Advertisement
Guest User

Untitled

a guest
Mar 26th, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. package fr.cedric.main;
  2.  
  3. import java.sql.*;
  4.  
  5. public class Main {
  6. // JDBC driver name and database URL
  7. static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  8. static final String DB_URL = "jdbc:mysql://localhost/bdd";
  9.  
  10. // Database credentials
  11. static final String USER = "root";
  12. static final String PASS = "";
  13.  
  14. public static void main(String[] args) {
  15. Connection conn = null;
  16. Statement stmt = null;
  17. try{
  18. //STEP 2: Register JDBC driver
  19. Class.forName("com.mysql.jdbc.Driver");
  20.  
  21. //STEP 3: Open a connection
  22. System.out.println("Connecting to database...");
  23. conn = DriverManager.getConnection(DB_URL,USER,PASS);
  24.  
  25. //STEP 4: Execute a query
  26. System.out.println("Creating statement...");
  27. stmt = conn.createStatement();
  28. String sql;
  29. sql = "SELECT userID FROM clients";
  30. ResultSet rs = stmt.executeQuery(sql);
  31.  
  32. //STEP 5: Extract data from result set
  33. while(rs.next()){
  34. //Retrieve by column name
  35. int id = rs.getInt("userID");
  36.  
  37.  
  38. //Display values
  39. System.out.print("ID: " + id + "\n");
  40. }
  41. //STEP 6: Clean-up environment
  42. rs.close();
  43. stmt.close();
  44. conn.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. stmt.close();
  56. }catch(SQLException se2){
  57. }// nothing we can do
  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.  
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement