コード例 #1
0
 private void orderBeer(int userID, int gameID, int amount) {
   Connection con = DatabaseConnector.getConnection();
   Statement stmt;
   try {
     int stationID = getStationID(con, userID, gameID);
     stmt = con.createStatement();
     // Bierbestellung eintragen
     stmt.executeUpdate(
         "INSERT INTO orders(sender_id,amount,week) VALUES("
             + getStationID(con, userID, gameID)
             + ","
             + amount
             + ","
             + getGameWeek(con, gameID)
             + ")");
     int stationType = getStationType(con, stationID);
     if (stationType == 0) setNextStationAction(con, stationID, ACTION_ORDER_BEER);
     else setNextStationAction(con, stationID, ACTION_COLLECT_DELIVERY);
     endOfTurn(con, gameID, stationID);
     con.commit();
     con.close();
   } catch (SQLException e) {
     try {
       con.rollback();
       con.close();
     } catch (SQLException e1) {
       e1.printStackTrace();
     }
     e.printStackTrace();
   }
 }
コード例 #2
0
  public void testPoolShrink() throws Exception {
    if (log.isDebugEnabled()) {
      log.debug("*** Starting testPoolShrink");
    }
    Field poolField = pds.getClass().getDeclaredField("pool");
    poolField.setAccessible(true);
    XAPool pool = (XAPool) poolField.get(pds);

    assertEquals(1, pool.inPoolSize());
    assertEquals(1, pool.totalPoolSize());

    Connection c1 = pds.getConnection();
    assertEquals(0, pool.inPoolSize());
    assertEquals(1, pool.totalPoolSize());

    Connection c2 = pds.getConnection();
    assertEquals(0, pool.inPoolSize());
    assertEquals(2, pool.totalPoolSize());

    c1.close();
    c2.close();

    Thread.sleep(1100); // leave enough time for the idle connections to expire
    TransactionManagerServices.getTaskScheduler().interrupt(); // wake up the task scheduler
    Thread.sleep(1200); // leave enough time for the scheduled shrinking task to do its work

    if (log.isDebugEnabled()) {
      log.debug("*** checking pool sizes");
    }
    assertEquals(1, pool.inPoolSize());
    assertEquals(1, pool.totalPoolSize());
  }
コード例 #3
0
  /**
   * Faz consulta no banco de dados e retorna apenas um dia com esse nome.
   *
   * @return
   */
  public Turno selectTurno(String nomeTurno) {
    Connection connection = Conexao.getConexao();
    try {

      String sql = "SELECT * FROM turno where descricao = ?;";
      PreparedStatement prest = connection.prepareStatement(sql);
      prest.setString(1, nomeTurno);
      ResultSet rs = prest.executeQuery();

      // Pega o primeiro registro do retorno da consulta
      if (rs.next()) {
        // Cria uma nova disciplina
        Turno turno = new Turno();
        // Pega os dados desse registro e guarda em variáveis
        int id = rs.getInt("idTurno");
        String nome = rs.getString("descricao");

        // Seta os dados na disciplina criada
        turno.setId(id);
        turno.setNome(nome);

        connection.close();
        return turno;
      } else {
        connection.close();
        return null;
      }
    } catch (SQLException ex) {
      System.out.println(ex.getMessage());
    }
    return null;
  }
コード例 #4
0
ファイル: AdminService.java プロジェクト: bahizi/gcit_library
  private void editBranch(LibraryBranch branch) {
    try {
      Connection conn = getConnection();
      System.out.println("Enter Branch's new name:");
      String name = getInputString();
      System.out.println("Enter Publisher's new address:");
      String address = getInputString();
      try {
        LibraryBranchDAO libDAO = new LibraryBranchDAO(conn);
        branch.setBranchName(name);
        branch.setAddress(address);
        libDAO.update(branch);
        conn.commit();
        conn.close();
      } catch (Exception e) {
        conn.rollback();
        conn.close();
      }

    } catch (Exception e) {
      // TODO Auto-generated catch block
      System.err.println("Error while connecting to database");
      e.printStackTrace();
    }
  }
コード例 #5
0
  public void afterPropertiesSet() throws Exception {

    dataSource =
        new PooledDataSource(
            ReflectUtil.getClassLoader(),
            "org.h2.Driver",
            "jdbc:h2:mem:DatabaseTablePrefixTest;DB_CLOSE_DELAY=1000;MVCC=TRUE;",
            "sa",
            "");

    // create schema in the
    Connection connection = dataSource.getConnection();
    connection.createStatement().execute("drop schema if exists SCHEMA1");
    connection.createStatement().execute("create schema SCHEMA1");
    connection.close();

    ProcessEngineConfigurationImpl config1 =
        createCustomProcessEngineConfiguration()
            .setProcessEngineName("DatabaseTablePrefixTest-engine1")
            .setDataSource(dataSource)
            .setDbMetricsReporterActivate(false)
            .setDatabaseSchemaUpdate("NO_CHECK"); // disable auto create/drop schema
    config1.setDatabaseTablePrefix("SCHEMA1.");
    ProcessEngine engine1 = config1.buildProcessEngine();

    // create the tables in SCHEMA1
    connection = dataSource.getConnection();
    connection.createStatement().execute("set schema SCHEMA1");
    engine1.getManagementService().databaseSchemaUpgrade(connection, "", "SCHEMA1");
    connection.close();

    engine1.close();
  }
コード例 #6
0
ファイル: AdminService.java プロジェクト: bahizi/gcit_library
  private void editBorrower(Borrower bor) {
    try {
      Connection conn = getConnection();
      System.out.println("Enter new name: [N/A to skip]");
      String name = getInputString();
      System.out.println("Enter new address: [N/A to skip]");
      String address = getInputString();
      System.out.println("Enter new phone: [N/A to skip]");
      String phone = getInputString();
      if (!name.equals("N/A")) {
        bor.setName(name);
      }
      if (!address.equals("N/A")) {
        bor.setAddress(address);
      }
      if (!phone.equals("N/A")) {
        bor.setPhone(phone);
      }

      try {
        BorrowerDAO borDAO = new BorrowerDAO(conn);
        borDAO.update(bor);
        conn.commit();
        conn.close();
      } catch (Exception e) {
        conn.rollback();
        conn.close();
      }

    } catch (Exception e) {
      // TODO Auto-generated catch block
      System.err.println("Error while connecting to database");
      e.printStackTrace();
    }
  }
コード例 #7
0
ファイル: AdminService.java プロジェクト: bahizi/gcit_library
  private void editPublisher(Publisher publisher) {
    try {
      Connection conn = getConnection();
      System.out.println("Enter Publisher's new name:");
      String name = getInputString();
      System.out.println("Enter Publisher's new address:");
      String address = getInputString();
      System.out.println("Enter Publisher's new phone:");
      String phone = getInputString();
      try {
        PublisherDAO pubDAO = new PublisherDAO(conn);
        publisher.setPublisherName(name);
        publisher.setPublisherAddress(address);
        publisher.setPublisherPhone(phone);
        pubDAO.update(publisher);
        conn.commit();
        conn.close();
      } catch (Exception e) {
        conn.rollback();
        conn.close();
      }

    } catch (Exception e) {
      // TODO Auto-generated catch block
      System.err.println("Error while connecting to database");
      e.printStackTrace();
    }
  }
コード例 #8
0
ファイル: TestHtmlReport.java プロジェクト: sreev/javamelody
  /**
   * Test.
   *
   * @throws Exception e
   */
  @Test
  public void testWriteConnections() throws Exception { // NOPMD
    final HtmlReport htmlReport =
        new HtmlReport(collector, null, javaInformationsList, Period.SEMAINE, writer);

    // avant initH2 pour avoir une liste de connexions vide
    htmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), false);
    assertNotEmptyAndClear(writer);
    // une connexion créée sur le thread courant
    final Connection connection = TestDatabaseInformations.initH2();
    // une deuxième connexion créée sur un thread qui n'existera plus quand le rapport sera généré
    final ExecutorService executorService = Executors.newFixedThreadPool(1);
    final Callable<Connection> task =
        new Callable<Connection>() {
          @Override
          public Connection call() {
            return TestDatabaseInformations.initH2();
          }
        };
    final Future<Connection> future = executorService.submit(task);
    final Connection connection2 = future.get();
    executorService.shutdown();
    try {
      htmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), false);
      assertNotEmptyAndClear(writer);
      htmlReport.writeConnections(JdbcWrapper.getConnectionInformationsList(), true);
      assertNotEmptyAndClear(writer);
    } finally {
      connection.close();
      connection2.close();
    }
  }
コード例 #9
0
ファイル: JdbcUtils.java プロジェクト: new-emacs/optiq
 SqlDialect get(DataSource dataSource) {
   Connection connection = null;
   try {
     connection = dataSource.getConnection();
     DatabaseMetaData metaData = connection.getMetaData();
     String productName = metaData.getDatabaseProductName();
     String productVersion = metaData.getDatabaseProductVersion();
     List key = Arrays.asList(productName, productVersion);
     SqlDialect dialect = map.get(key);
     if (dialect == null) {
       final SqlDialect.DatabaseProduct product =
           SqlDialect.getProduct(productName, productVersion);
       dialect = new SqlDialect(product, productName, metaData.getIdentifierQuoteString());
       map.put(key, dialect);
     }
     connection.close();
     connection = null;
     return dialect;
   } catch (SQLException e) {
     throw new RuntimeException(e);
   } finally {
     if (connection != null) {
       try {
         connection.close();
       } catch (SQLException e) {
         // ignore
       }
     }
   }
 }
コード例 #10
0
  /**
   * @param ds
   * @param userId
   * @param e2bExchangeId
   * @param initOrFollow
   * @throws SQLException
   */
  public void importE2bData(String userId, String e2bExchangeId) throws SQLException {
    log.info("### in importE2bData (");
    Connection con = null;

    try {

      con = ds.getConnection();
      String sql = "{ call ? := LAU_E2B_INBOUND.import_e2b_message(?,?,?,?,?,?,?,?)}";
      CallableStatement stmt = con.prepareCall(sql);

      stmt.registerOutParameter(1, OracleTypes.VARCHAR); // 1
      stmt.setString(2, e2bExchangeId); // P_CLOB_ID NUMBER , :2
      stmt.registerOutParameter(3, OracleTypes.VARCHAR); // P_ERR_MSG OUT
      // varchar2, :3
      stmt.registerOutParameter(4, OracleTypes.VARCHAR); // P_MSG OUT
      // varchar2, :4
      stmt.registerOutParameter(5, OracleTypes.VARCHAR); // P_REPORT_ID_OUT
      // out VARCHAR2,
      // :5
      stmt.registerOutParameter(6, OracleTypes.VARCHAR); // P_LAU_REPORT_ID_OUT
      // out VARCHAR2,
      // :6
      stmt.registerOutParameter(7, OracleTypes.NUMBER); // P_ACK_ID_OUT out
      // NUMBER, :7

      stmt.setString(8, userId); // P_USER_ID varchar2, :8
      stmt.setString(9, "N"); // P_MULTICASES VARCHAR2 DEFAULT 'N', :9
      // stmt.setString(10, initOrFollow);// P_PROCESSING_MODE VARCHAR2
      // DEFAULT 'AUTOMATED', :10
      // stmt.setString(11, "Y");// P_ACK VARCHAR2 DEFAULT 'Y', :11
      // stmt.setString(12, "N"); // P_DISPLAY_OUTPUT VARCHAR2 DEFAULT 'N'
      // :12
      log.info("15====");
      log.info(sql);
      stmt.execute();
      // FUNCTION output

      // int update = stmt.getInt(1);
      String retVal = stmt.getString(1); // 0 - Error, > 0 success
      String strError = stmt.getString(3); // P_ERR_MSG OUT varchar2, :3
      String strMsg = stmt.getString(4); // P_MSG OUT varchar2, :4
      String strRepId = stmt.getString(5); // P_REPORT_ID_OUT out VARCHAR2,
      // :5
      String strLauRepId = stmt.getString(6); // P_LAU_REPORT_ID_OUT out
      // VARCHAR2, :6
      String ackId = Integer.toString(stmt.getInt(7)); // P_ACK_ID_OUT out
      // NUMBER, :7

      log.info("Funtion returned ...:" + retVal + "," + strError + "," + strRepId);
      stmt.close();
      con.close();

    } finally {
      try {
        if (con != null) con.close();
      } catch (Exception e) {
        log.error(e, e);
      }
    }
  }
コード例 #11
0
  @Test
  public void testUpsertValuesWithDate() throws Exception {
    long ts = nextTimestamp();
    Properties props = new Properties();
    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts));
    Connection conn = DriverManager.getConnection(getUrl(), props);
    conn.createStatement()
        .execute("create table UpsertDateTest (k VARCHAR not null primary key,date DATE)");
    conn.close();

    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 5));
    conn = DriverManager.getConnection(getUrl(), props);
    conn.createStatement()
        .execute("upsert into UpsertDateTest values ('a',to_date('2013-06-08 00:00:00'))");
    conn.commit();
    conn.close();

    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10));
    conn = DriverManager.getConnection(getUrl(), props);
    ResultSet rs =
        conn.createStatement().executeQuery("select k,to_char(date) from UpsertDateTest");
    assertTrue(rs.next());
    assertEquals("a", rs.getString(1));
    assertEquals("2013-06-08 00:00:00", rs.getString(2));
  }
コード例 #12
0
 @Ignore("[CALCITE-687] Make RemoteDriverTest.testStatementLifecycle thread-safe")
 @Test
 public void testConnectionIsolation() throws Exception {
   final String sql = "select * from (values (1, 'a'))";
   Connection conn1 = ljs();
   Connection conn2 = ljs();
   Cache<String, Connection> connectionMap =
       QuasiRemoteJdbcServiceFactory.getRemoteConnectionMap((AvaticaConnection) conn1);
   assertEquals("connection cache should start empty", 0, connectionMap.size());
   PreparedStatement conn1stmt1 = conn1.prepareStatement(sql);
   assertEquals(
       "statement creation implicitly creates a connection server-side", 1, connectionMap.size());
   PreparedStatement conn2stmt1 = conn2.prepareStatement(sql);
   assertEquals(
       "statement creation implicitly creates a connection server-side", 2, connectionMap.size());
   AvaticaPreparedStatement s1 = (AvaticaPreparedStatement) conn1stmt1;
   AvaticaPreparedStatement s2 = (AvaticaPreparedStatement) conn2stmt1;
   assertFalse(
       "connection id's should be unique",
       s1.handle.connectionId.equalsIgnoreCase(s2.handle.connectionId));
   conn2.close();
   assertEquals("closing a connection closes the server-side connection", 1, connectionMap.size());
   conn1.close();
   assertEquals("closing a connection closes the server-side connection", 0, connectionMap.size());
 }
コード例 #13
0
ファイル: TestSSL.java プロジェクト: Leolh/hive
  /**
   * * Test SSL client connection to SSL server
   *
   * @throws Exception
   */
  @Test
  public void testSSLConnectionWithProperty() throws Exception {
    setSslConfOverlay(confOverlay);
    // Test in binary mode
    setBinaryConfOverlay(confOverlay);
    // Start HS2 with SSL
    miniHS2.start(confOverlay);

    System.setProperty(JAVA_TRUST_STORE_PROP, dataFileDir + File.separator + TRUST_STORE_NAME);
    System.setProperty(JAVA_TRUST_STORE_PASS_PROP, KEY_STORE_PASSWORD);
    // make SSL connection
    hs2Conn =
        DriverManager.getConnection(
            miniHS2.getJdbcURL() + ";ssl=true", System.getProperty("user.name"), "bar");
    hs2Conn.close();
    miniHS2.stop();

    // Test in http mode
    setHttpConfOverlay(confOverlay);
    miniHS2.start(confOverlay);
    // make SSL connection
    hs2Conn =
        DriverManager.getConnection(
            miniHS2.getJdbcURL("default", SSL_CONN_PARAMS), System.getProperty("user.name"), "bar");
    hs2Conn.close();
  }
コード例 #14
0
 private void brewBeer(int userID, int gameID, int amount) {
   Connection con = DatabaseConnector.getConnection();
   Statement stmt;
   try {
     int stationID = getStationID(con, userID, gameID);
     stmt = con.createStatement();
     // Bierlieferung eintragen (Produktion)
     stmt.executeUpdate(
         "INSERT INTO deliveries(receiver_id,amount,week) VALUES("
             + stationID
             + ","
             + amount
             + ","
             + (getGameWeek(con, gameID) + 2)
             + ")");
     setNextStationAction(con, stationID, ACTION_COLLECT_DELIVERY);
     endOfTurn(con, gameID, stationID);
     con.commit();
     con.close();
   } catch (SQLException e) {
     try {
       con.rollback();
       con.close();
     } catch (SQLException e1) {
       e1.printStackTrace();
     }
     e.printStackTrace();
   }
 }
コード例 #15
0
  public void retrieve10MaxTradesStockList(
      ErrorObject error, DatabaseClass db, Date start, Date end) {

    Connection conn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;
    String sql =
        "select ticker, name, isin, currency, "
            + "marketplace, listname, sum(trades) as tradeSum "
            + "from stock_information "
            + "where information_date <= ? and information_date >= ? "
            + "group by ticker, name, isin, currency, marketplace, listname "
            + "order by tradeSum desc ";
    this.clear();

    try {
      conn = DriverManager.getConnection(db.getUrl(), db.getUsr(), db.getPwd());
      conn.setAutoCommit(false);

      pst = conn.prepareStatement(sql);
      long date1 = end.getTime();
      java.sql.Date sqlDate1 = new java.sql.Date(date1);
      pst.setDate(1, sqlDate1);

      long date2 = start.getTime();
      java.sql.Date sqlDate2 = new java.sql.Date(date2);
      pst.setDate(2, sqlDate2);

      rs = pst.executeQuery();
      int i = 0;
      while (rs.next()) {
        if (i < 10) {
          StockInformation si = new StockInformation();
          si.setTicker(rs.getString(1));
          si.setName(rs.getString(2));
          si.setIsin(rs.getString(3));
          si.setCurrency(rs.getString(4));
          si.setMarketplace(rs.getString(5));
          si.setListname(rs.getString(6));
          si.setPeriodSumTrades(new Integer(rs.getInt(7)));
          this.add(si);
          i++;
        }
      }
      rs.close();
      conn.commit();
      pst.close();
      conn.close();
    } catch (SQLException e) {
      System.out.println("DB Error: " + e.getMessage());
      error.setError(true);
      error.setMessage(e.getMessage());
      if (conn != null) {
        try {
          conn.close();
        } catch (SQLException e2) {
        }
      }
    }
  }
コード例 #16
0
  @Test
  public void testAllowDropParentTableWithCascadeAndSingleTenantTable() throws Exception {
    long ts = nextTimestamp();
    Properties props = new Properties();
    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts));
    Connection conn = DriverManager.getConnection(getUrl(), props);
    Connection connTenant = null;

    try {
      // Drop Parent Table
      conn.createStatement().executeUpdate("DROP TABLE " + PARENT_TABLE_NAME + " CASCADE");
      conn.close();

      props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10));
      connTenant = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL, props);

      validateTenantViewIsDropped(conn);
    } finally {
      if (conn != null) {
        conn.close();
      }
      if (connTenant != null) {
        connTenant.close();
      }
    }
  }
コード例 #17
0
ファイル: AdminService.java プロジェクト: bahizi/gcit_library
 private void addBorrower() {
   try {
     Connection conn = getConnection();
     try {
       BorrowerDAO borDAO = new BorrowerDAO(conn);
       Borrower toAdd = new Borrower();
       System.out.println("What is the borrower's name?");
       String borName = getInputString();
       System.out.println("What is the borrower's address?");
       String borAddress = getInputString();
       System.out.println("What is the borrower's phone address?");
       String borPhone = getInputString();
       toAdd.setName(borName);
       toAdd.setAddress(borAddress);
       toAdd.setPhone(borPhone);
       borDAO.create(toAdd);
       conn.commit();
       conn.close();
     } catch (Exception e) {
       conn.rollback();
       conn.close();
       e.printStackTrace();
     }
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  public void closeConnections() throws SQLException {
    if (itemPreparedStatement != null) {
      itemPreparedStatement.close();
    }

    if (itemConnection != null) {
      itemConnection.close();
    }

    if (holdingsPreparedStatement != null) {
      holdingsPreparedStatement.close();
    }

    if (holdingsConnection != null) {
      holdingsConnection.close();
    }

    if (bibResultSet != null) {
      bibResultSet.close();
    }
    if (bibStatement != null) {
      bibStatement.close();
    }

    if (bibConnection != null) {
      bibConnection.close();
    }
    if (connection != null) {
      connection.close();
    }
  }
コード例 #19
0
ファイル: AdminService.java プロジェクト: bahizi/gcit_library
 // gather the necessary information to add a publisher
 private void addPublisher() {
   try {
     Connection conn = getConnection();
     try {
       PublisherDAO pubDAO = new PublisherDAO(conn);
       Publisher toAdd = new Publisher();
       System.out.println("What is the Publisher's name?");
       String pubName = getInputString();
       System.out.println("What is the Publisher's address?");
       String pubAddress = getInputString();
       System.out.println("What is the Publisher's phone number?");
       String pubPhone = getInputString();
       toAdd.setPublisherName(pubName);
       toAdd.setPublisherAddress(pubAddress);
       toAdd.setPublisherPhone(pubPhone);
       pubDAO.create(toAdd);
       conn.commit();
       conn.close();
     } catch (Exception e) {
       conn.rollback();
       conn.close();
       e.printStackTrace();
     }
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
コード例 #20
0
  @Test
  public void multipleSetDataSourceCalls() throws Exception {
    DriverDataSource dataSource1 =
        new DriverDataSource(null, "jdbc:h2:mem:flyway_db_1;DB_CLOSE_DELAY=-1", "sa", "");

    DriverDataSource dataSource2 =
        new DriverDataSource(null, "jdbc:h2:mem:flyway_db_2;DB_CLOSE_DELAY=-1", "sa", "");

    Connection connection1 = dataSource1.getConnection();
    Connection connection2 = dataSource2.getConnection();

    Schema schema1 = new H2DbSupport(connection1).getSchema("PUBLIC");
    Schema schema2 = new H2DbSupport(connection2).getSchema("PUBLIC");

    assertTrue(schema1.empty());
    assertTrue(schema2.empty());

    Flyway flyway = new Flyway();

    flyway.setDataSource(dataSource1);
    flyway.setDataSource(dataSource2);

    flyway.setLocations("migration/sql");
    flyway.migrate();

    assertTrue(schema1.empty());
    assertFalse(schema2.empty());

    connection1.close();
    connection2.close();
  }
コード例 #21
0
ファイル: AdminService.java プロジェクト: bahizi/gcit_library
 private void addLibrary() {
   try {
     Connection conn = getConnection();
     try {
       LibraryBranchDAO libDAO = new LibraryBranchDAO(conn);
       LibraryBranch toAdd = new LibraryBranch();
       System.out.println("What is the new branch's name?");
       String libName = getInputString();
       System.out.println("What is the Publisher's address?");
       String libAddress = getInputString();
       toAdd.setBranchName(libName);
       toAdd.setAddress(libAddress);
       libDAO.create(toAdd);
       conn.commit();
       conn.close();
     } catch (Exception e) {
       conn.rollback();
       conn.close();
       e.printStackTrace();
     }
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
コード例 #22
0
  public void test() throws Exception {

    Connection conn = newConnection();
    Statement statement;
    int updateCount;

    try {
      statement = conn.createStatement();

      ResultSet rs =
          statement.executeQuery("call \"org.hsqldb.test.TestStoredProcedure.procTest1\"()");

      rs.next();

      int cols = rs.getInt(1);

      assertTrue("test result not correct", cols == 2);
    } catch (Exception e) {
      assertTrue("unable to execute call to procedure", false);
    } finally {
      conn.close();
    }

    conn = newConnection();

    try {
      statement = conn.createStatement();
    } catch (Exception e) {
      assertTrue("unexpected error", false);
    } finally {
      conn.close();
    }
  }
コード例 #23
0
 public static void HydraTask_populateMusicDB() {
   if (musicHelper == null) {
     musicHelper = new MusicHelper();
   }
   try {
     if (hasDerbyServer) {
       Connection dConn = musicHelper.getDiscConnection();
       MusicPopulator.addToTables(
           dConn,
           MusicPrms.getNumGeneratedArtists(),
           MusicPrms.getNumGeneratedAlbums(),
           MusicPrms.getNumGeneratedCopyrightOwners(),
           MusicPrms.getNumGeneratedSongs(),
           MusicPrms.getNumGeneratedGenres(),
           MusicPrms.getNumGeneratedTags(),
           MusicPrms.getNumGeneratedTracks());
       dConn.close();
     }
     Connection gConn = musicHelper.getGFEConnection();
     MusicPopulator.addToTables(
         gConn,
         MusicPrms.getNumGeneratedArtists(),
         MusicPrms.getNumGeneratedAlbums(),
         MusicPrms.getNumGeneratedCopyrightOwners(),
         MusicPrms.getNumGeneratedSongs(),
         MusicPrms.getNumGeneratedGenres(),
         MusicPrms.getNumGeneratedTags(),
         MusicPrms.getNumGeneratedTracks());
     gConn.close();
   } catch (SQLException sqle) {
     SQLHelper.handleSQLException(sqle);
   }
 }
コード例 #24
0
ファイル: ClienteFacade.java プロジェクト: David9224/BabelApp
 public List<Cliente> getAllClientes() throws Exception {
   Connection conexion = connection.conexion();
   try {
     String SQL = " select * from Cliente ";
     PreparedStatement stmt = conexion.prepareStatement(SQL);
     ResultSet rs = stmt.executeQuery();
     Cliente cliente = null;
     List<Cliente> listaCliente = new ArrayList<>();
     while (rs.next()) {
       cliente = new Cliente();
       cliente.setCedula(rs.getInt(1));
       cliente.setNombres(rs.getString(2));
       cliente.setApellidos(rs.getString(3));
       cliente.setFecha_nacimiento(rs.getDate(4));
       cliente.setDireccion(rs.getString(5));
       cliente.setEmail(rs.getString(6));
       cliente.setTelefono(rs.getInt(7));
       listaCliente.add(cliente);
     }
     rs.close();
     stmt.close();
     conexion.close();
     return listaCliente;
   } catch (Exception e) {
     conexion.close();
     throw new Exception("Error getAllClientes: " + e.toString());
   }
 }
コード例 #25
0
  public void testPoolGrowth() throws Exception {
    if (log.isDebugEnabled()) {
      log.debug("*** Starting testPoolGrowth");
    }
    Field poolField = pds.getClass().getDeclaredField("pool");
    poolField.setAccessible(true);
    XAPool pool = (XAPool) poolField.get(pds);

    assertEquals(1, pool.inPoolSize());
    assertEquals(1, pool.totalPoolSize());

    Connection c1 = pds.getConnection();
    assertEquals(0, pool.inPoolSize());
    assertEquals(1, pool.totalPoolSize());

    Connection c2 = pds.getConnection();
    assertEquals(0, pool.inPoolSize());
    assertEquals(2, pool.totalPoolSize());

    try {
      pds.getConnection();
      fail("should not be able to get a 3rd connection");
    } catch (SQLException ex) {
      assertEquals(
          "unable to get a connection from pool of a PoolingDataSource containing an XAPool of resource pds with 2 connection(s) (0 still available)",
          ex.getMessage());
    }

    c1.close();
    c2.close();
    assertEquals(2, pool.inPoolSize());
    assertEquals(2, pool.totalPoolSize());
  }
コード例 #26
0
ファイル: ClienteFacade.java プロジェクト: David9224/BabelApp
 /**
  * @param cedula
  * @return
  * @throws java.lang.Exception @Fecha 16/11/2015 @Observacion busca el cliente por cedula
  */
 public Cliente buscarCliente(long cedula) throws Exception {
   Connection conexion = connection.conexion();
   try {
     String SQL = " select * from cliente " + "     where cedula = ? ";
     PreparedStatement stmt = conexion.prepareStatement(SQL);
     stmt.setLong(1, cedula);
     Cliente cliente = null;
     ResultSet rs = stmt.executeQuery();
     while (rs.next()) {
       cliente = new Cliente();
       cliente.setCedula(rs.getInt(1));
       cliente.setNombres(rs.getString(2));
       cliente.setApellidos(rs.getString(3));
       cliente.setFecha_nacimiento(rs.getDate(4));
       cliente.setDireccion(rs.getString(5));
       cliente.setEmail(rs.getString(6));
       cliente.setTelefono(rs.getInt(7));
     }
     rs.close();
     stmt.close();
     conexion.close();
     return cliente;
   } catch (Exception e) {
     conexion.close();
     throw new Exception("Error Buscar Cliente: " + e.getMessage());
   }
 }
コード例 #27
0
  public void testPoolReset() throws Exception {
    if (log.isDebugEnabled()) {
      log.debug("*** Starting testPoolReset");
    }

    Field poolField = pds.getClass().getDeclaredField("pool");
    poolField.setAccessible(true);
    XAPool pool = (XAPool) poolField.get(pds);

    assertEquals(1, pool.inPoolSize());
    assertEquals(1, pool.totalPoolSize());

    Connection c1 = pds.getConnection();
    assertEquals(0, pool.inPoolSize());
    assertEquals(1, pool.totalPoolSize());

    Connection c2 = pds.getConnection();
    assertEquals(0, pool.inPoolSize());
    assertEquals(2, pool.totalPoolSize());

    c1.close();
    c2.close();

    pds.reset();

    assertEquals(1, pool.inPoolSize());
    assertEquals(1, pool.totalPoolSize());
  }
コード例 #28
0
  private List<Appointment> genericFindAppointments(
      Connection conn, PreparedStatement findStatement) {
    try {
      ResultSet rs = findStatement.executeQuery();

      int nrRows = 0;
      if (rs.last()) {
        nrRows = rs.getRow();
      }
      rs.beforeFirst();

      ArrayList<Appointment> apps = new ArrayList<Appointment>(nrRows);
      while (rs.next()) {
        apps.add((Appointment) load(rs));
      }

      conn.close();

      return apps;
    } catch (SQLException e) {
      try {
        conn.close();
      } catch (SQLException se) {
        System.out.println("An SQL exceptions occured: " + se.getMessage());
      }

      System.out.println("An SQL exceptions occured: " + e.getMessage());

      return null;
    }
  }
コード例 #29
0
ファイル: DbClient.java プロジェクト: shiprabanga/Cloud
  public static UserLoginResponse userLogIn(final UserLoginRequest userInfo)
      throws SQLException, IOException, PropertyVetoException, ClassNotFoundException {
    final String query = Query.SELECT_USER_DETAILS.toString();
    final Connection conn = DataSource.getInstance().getConnection();
    final PreparedStatement stmt = conn.prepareStatement(query);
    stmt.setString(1, userInfo.getUserId());

    ResultSet rs = stmt.executeQuery();
    if (!rs.next()) {
      conn.close();
      throw new SQLException("User ID " + userInfo.getUserId() + " does not exist.");
    } else {
      if (!rs.getString("password").equals(userInfo.getPassword())) {
        conn.close();
        throw new SQLException("Authentication problem.");
      }
      UserLoginResponse resp =
          new UserLoginResponse(
              "200",
              "Login Success.",
              userInfo.getUserId(),
              rs.getString("name"),
              rs.getString("password"),
              rs.getString("clickDelayInSeconds"),
              rs.getString("uploadIntervalInSeconds"));
      conn.close();
      return resp;
    }
  }
コード例 #30
0
 private String acceptNextOrder(int userID, int gameID) {
   Connection con = DatabaseConnector.getConnection();
   Statement stmt;
   ResultSet rs;
   try {
     int stationID = getStationID(con, userID, gameID);
     stmt = con.createStatement();
     rs =
         stmt.executeQuery(
             "SELECT amount FROM orders WHERE sender_id="
                 + getSellerID(con, stationID)
                 + " AND week="
                 + getGameWeek(con, gameID));
     if (rs.next()) {
       int amount = rs.getInt("amount");
       stmt.executeUpdate(
           "UPDATE stations SET backorder=backorder+" + amount + " WHERE station_id=" + stationID);
     }
     setNextStationAction(con, stationID, ACTION_DELIVER_BEER);
     con.commit();
     con.close();
   } catch (SQLException e) {
     try {
       con.rollback();
       con.close();
     } catch (SQLException e1) {
       e1.printStackTrace();
     }
     e.printStackTrace();
   }
   Gson gson = new Gson();
   return gson.toJson("");
 }