Guest User

Untitled

a guest
Oct 24th, 2017
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. package com.tutorialsdojo;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8. import java.sql.ResultSetMetaData;
  9.  
  10. /**
  11. * How to connect to a mySQL Database.
  12. *
  13. * @author Jon Bonso
  14. *
  15. */
  16. public class DatabaseConnection {
  17.  
  18. public static void main(String[] args) {
  19. try {
  20. connectToDB();
  21. }catch (Exception e){
  22. e.printStackTrace();
  23. }
  24. }
  25.  
  26.  
  27. /**
  28. * Connect to MySQL Database
  29. * @throws SQLException
  30. */
  31. private static void connectToDB() throws SQLException{
  32.  
  33. // 1. Get the Connection instance using the DriverManager.getConnection() method
  34. // with your MySQL Database Credentails
  35.  
  36. Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tutorialsdojo",
  37. "tutorialsdojo", "P@sSword123");
  38.  
  39. System.out.println("LOG: Connection Established!");
  40.  
  41. // 2. Execute your SQL Query using conn.createStatement.executeQuery()
  42. // and get the result as a ResultSet object.
  43. // with your MySQL Database Credentails
  44.  
  45. ResultSet rs = conn.createStatement().executeQuery("select now()");
  46. ResultSetMetaData rsmd = rs.getMetaData();
  47.  
  48. System.out.println("Query Results: \n\n");
  49.  
  50. // Show Column Names
  51. getColumnNames(rsmd);
  52.  
  53. // Getting the Results
  54. while (rs.next()){
  55. for ( int i=1; i <= rsmd.getColumnCount(); i++){;
  56. System.out.print(rs.getString(i) + "\t\t");
  57. }
  58.  
  59. System.out.println();
  60. }
  61. }
  62.  
  63. /**
  64. * Shows the Column Names
  65. * @param rs
  66. * @throws SQLException
  67. */
  68. private static void getColumnNames(ResultSetMetaData rsmd) throws SQLException{
  69. // Getting the list of COLUMN Names
  70. for ( int i=1; i <= rsmd.getColumnCount(); i++){
  71. System.out.print(rsmd.getColumnName(i) + "\t\t|");
  72. }
  73.  
  74. System.out.println("");
  75. }
  76. }
Add Comment
Please, Sign In to add comment