Advertisement
Guest User

Untitled

a guest
Oct 6th, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.42 KB | None | 0 0
  1. /**
  2.  
  3. * @param args the command line arguments
  4.  
  5. */
  6.  
  7. public static void main(String[] args) {
  8.  
  9.  
  10. final String DATABASE_URL =
  11.  
  12. "jdbc:mysql://localhost:3306/bookauthordb";
  13.  
  14. final String SELECT_QUERY =
  15.  
  16. "SELECT id, firstName, lastName FROM author";
  17.  
  18. // use try-with-resources to connect to and query the database
  19.  
  20. try (
  21.  
  22. // establish database connection
  23.  
  24. Connection connection = DriverManager.getConnection(
  25.  
  26. DATABASE_URL, "root", "Sheridan");
  27.  
  28. // Create query statement
  29.  
  30. Statement statement = connection.createStatement();
  31.  
  32. // execute query and get result as ResultSet object
  33.  
  34. ResultSet queryResult = statement.executeQuery(SELECT_QUERY))
  35.  
  36. {
  37.  
  38. // get ResultSet's meta data
  39.  
  40. ResultSetMetaData metaData = queryResult.getMetaData();
  41.  
  42. int numberOfColumns = metaData.getColumnCount();
  43.  
  44.  
  45. System.out.printf("Authors Table of Books Database:%n%n");
  46.  
  47. // display the names of the columns in the ResultSet
  48.  
  49. for (int i = 1; i <= numberOfColumns; i++)
  50.  
  51. System.out.printf("%-8s\t", metaData.getColumnName(i));
  52.  
  53. System.out.println();
  54.  
  55.  
  56. // display query results
  57.  
  58. while (queryResult.next())
  59.  
  60. {
  61.  
  62. for (int i = 1; i <= numberOfColumns; i++)
  63.  
  64. System.out.printf("%-8s\t", queryResult.getObject(i));
  65.  
  66. System.out.println();
  67.  
  68. }
  69.  
  70. } // AutoCloseable objects' close methods are called now
  71.  
  72. catch (SQLException sqlException)
  73.  
  74. {
  75.  
  76. sqlException.printStackTrace();
  77.  
  78. }
  79.  
  80. }
  81.  
  82.  
  83. } //End of JDBC-DB-Example1 class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement