/*
* Copyright (c) 2006-2014 Rogério Liesenfeld
* This file is subject to the terms of the MIT license (see LICENSE.txt).
*/ /*...*/ |
||
| 5 | package orderMngr.service; |
|
|
||
/**
* A static facade for database access through JDBC.
* It assumes the application can use a single global DB connection.
* <p/>
* This class is just for the sake of demonstrating the capabilities of the available mocking APIs.
* In the real world, such direct use of JDBC is not a practical approach, leading to long and complicated methods,
* with excessive amounts of mocking in the corresponding unit tests.
* A better approach is to use a higher-level abstraction for access to persistent state, which allows both production
* and test code to be significantly smaller.
*/ /*...*/ |
||
| 19 | public final class Database |
|
| 20 | { |
|
| 21 | private static Connection connection; |
|
| 23 | 0 | private Database() {}
|
| 25 | public static synchronized Connection connection() |
|
| 26 | { |
|
| 0 | Path coverage: 0/2 A: 0 B: 0 | |
| 27 | 0 | if (connection == null) {
|
| 28 | try { |
|
| 29 | 0 | connection = DriverManager.getConnection("jdbc:test:ordersDB");
|
| 30 | } |
|
| 31 | 0 | catch (SQLException e) {
|
| 32 | 0 | throw new RuntimeException(e); |
| 33 | 0 | } |
| 34 | } |
|
| 36 | 0 | return connection; |
| 37 | } |
|
| 39 | public static void executeInsertUpdateOrDelete(String sql, Object... args) |
|
| 40 | { |
|
| 0 | Path coverage: 0/3 A: 0 B: 0 C: 0 | |
| 41 | 0 | try (PreparedStatement stmt = createStatement(sql, args)) {
|
| 42 | 0 | stmt.executeUpdate(); |
| 43 | 0 | }
|
| 44 | 0 | catch (SQLException e) {
|
| 45 | 0 | throw new RuntimeException(e); |
| 46 | 0 | } |
| 47 | 0 | } |
| 49 | private static PreparedStatement createStatement(String sql, Object... args) throws SQLException |
|
| 50 | { |
|
| 2 | Path coverage: 1/2 A: 0 B: 2 | |
| 51 | 2 | PreparedStatement stmt = connection().prepareStatement(sql); |
| 52 | 2 | int i = 1; |
| 54 | 4 | for (Object arg : args) { |
| 55 | 2 | stmt.setObject(i, arg); |
| 56 | 2 | i++; |
| 57 | } |
|
| 59 | 2 | return stmt; |
| 60 | } |
|
| 62 | public static void closeStatement(ResultSet result) |
|
| 63 | { |
|
| 2 | Path coverage: 1/2 A: 0 B: 2 | |
| 64 | 2 | if (result != null) {
|
| 65 | try { |
|
| 66 | 2 | result.getStatement().close(); |
| 67 | } |
|
| 68 | 0 | catch (SQLException e) {
|
| 69 | 0 | throw new RuntimeException(e); |
| 70 | 2 | } |
| 71 | } |
|
| 72 | 2 | } |
| 74 | public static ResultSet executeQuery(String sql, Object... args) |
|
| 75 | { |
|
| 76 | try { |
|
| 77 | 2 | PreparedStatement stmt = createStatement(sql, args); |
| 78 | 2 | return stmt.executeQuery(); |
| 79 | } |
|
| 80 | 0 | catch (SQLException e) {
|
| 81 | 0 | throw new RuntimeException(e); |
| 82 | } |
|
| 83 | } |
|
| 84 | } |
|