Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- final String DATABASE_URL =
- "jdbc:mysql://localhost:3306/bookauthordb";
- final String SELECT_QUERY =
- "SELECT id, firstName, lastName FROM author";
- // use try-with-resources to connect to and query the database
- try (
- // establish database connection
- Connection connection = DriverManager.getConnection(
- DATABASE_URL, "root", "Sheridan");
- // Create query statement
- Statement statement = connection.createStatement();
- // execute query and get result as ResultSet object
- ResultSet queryResult = statement.executeQuery(SELECT_QUERY))
- {
- // get ResultSet's meta data
- ResultSetMetaData metaData = queryResult.getMetaData();
- int numberOfColumns = metaData.getColumnCount();
- System.out.printf("Authors Table of Books Database:%n%n");
- // display the names of the columns in the ResultSet
- for (int i = 1; i <= numberOfColumns; i++)
- System.out.printf("%-8s\t", metaData.getColumnName(i));
- System.out.println();
- // display query results
- while (queryResult.next())
- {
- for (int i = 1; i <= numberOfColumns; i++)
- System.out.printf("%-8s\t", queryResult.getObject(i));
- System.out.println();
- }
- } // AutoCloseable objects' close methods are called now
- catch (SQLException sqlException)
- {
- sqlException.printStackTrace();
- }
- }
- } //End of JDBC-DB-Example1 class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement