Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ch.bzz.book.data;
- import ch.bzz.book.service.Config;
- import javax.naming.InitialContext;
- import javax.naming.NamingException;
- import javax.sql.DataSource;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- /**
- * data access for book entity
- * <p>
- * M151: BookDB
- *
- * @author Marcel Suter
- * @version 1.0
- * @since 2019-10-13
- */
- public class BookDao {
- /**
- * TODO
- *
- * @return
- */
- public Integer count() {
- // TODO establish connection
- // TODO count books in database
- Connection connection = null;
- Integer bookCount = null;
- ResultSet resultSet = null;
- PreparedStatement prepStmt = null; // import java.sql.PreparedStatement
- try{
- InitialContext initialContext = new InitialContext();
- DataSource dataSource = (DataSource) initialContext.lookup(Config.getProperty("jdbcRessource"));
- connection = dataSource.getConnection();
- String sqlQuery = "SELECT count(bookUUID) FROM Book";
- try {
- prepStmt = connection.prepareStatement(sqlQuery);
- resultSet = prepStmt.executeQuery();
- if (resultSet.next()) { // resultSet contains rows
- bookCount = resultSet.getInt(1); // get the value of the first attribute
- }
- } catch (SQLException sqlEx) {
- sqlEx.printStackTrace();
- throw new RuntimeException();
- } finally { //schliess die connection
- try {
- if (resultSet != null)
- resultSet.close();
- if (prepStmt != null)
- prepStmt.close();
- if (connection != null)
- connection.close();
- } catch (SQLException sqlEx) {
- sqlEx.printStackTrace();
- throw new RuntimeException();
- }
- }
- } catch (NamingException nameEx) { // import javax.naming.NamingException
- nameEx.printStackTrace();
- throw new RuntimeException();
- } catch (SQLException sqlEx) { // import java.sql.SQLException
- sqlEx.printStackTrace();
- throw new RuntimeException();
- }
- return bookCount; // FIXME return the number of books
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement