orderMngmntWebapp\src\orderMngr\service\Database.java
 
/* * Copyright (c) 2006 Rogério Liesenfeld * This file is subject to the terms of the MIT license (see LICENSE.txt). */
/*...*/
5 
package orderMngr.service;
 
 
import java.sql.*;
import ...
 
 
/** * 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 
   private Database() {}
 
25 
   public static synchronized Connection connection()
26 
   {
0 Path coverage: 0/2 A: 0 B: 0
27 
      if (connection == null) {
28 
         try {
29 
            connection = DriverManager.getConnection("jdbc:test:ordersDB");
30 
         }
31 
         catch (SQLException e) {
32 
            throw new RuntimeException(e);
33 
         }
34 
      }
 
36 
      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 
      try (PreparedStatement stmt = createStatement(sql, args)) {
42 
         stmt.executeUpdate();
43 
      }
44 
      catch (SQLException e) {
45 
         throw new RuntimeException(e);
46 
      }
47 
   }
 
49 
   private static PreparedStatement createStatement(String sql, Object... args) throws SQLException
50 
   {
0 Path coverage: 0/2 A: 0 B: 0
51 
      PreparedStatement stmt = connection().prepareStatement(sql);
52 
      int i = 1;
 
54 
      for (Object arg : args) {
55 
         stmt.setObject(i, arg);
56 
         i++;
57 
      }
 
59 
      return stmt;
60 
   }
 
62 
   public static void closeStatement(ResultSet result)
63 
   {
0 Path coverage: 0/2 A: 0 B: 0
64 
      if (result != null) {
65 
         try {
66 
            result.getStatement().close();
67 
         }
68 
         catch (SQLException e) {
69 
            throw new RuntimeException(e);
70 
         }
71 
      }
72 
   }
 
74 
   public static ResultSet executeQuery(String sql, Object... args)
75 
   {
76 
      try {
77 
         PreparedStatement stmt = createStatement(sql, args);
78 
         return stmt.executeQuery();
79 
      }
80 
      catch (SQLException e) {
81 
         throw new RuntimeException(e);
82 
      }
83 
   }
84 
}