List of usage examples for javax.sql DataSource getConnection
Connection getConnection() throws SQLException;
Attempts to establish a connection with the data source that this DataSource object represents.
From source file:Controllers.ReportController.java
public Patient[] fetchAppointments(int departmentId, java.sql.Date date) { Patient[] patients = null;//from w w w . j a va 2s . com try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("jdbc/medicalCareDataSource"); connection = ds.getConnection(); PreparedStatement pstmt = connection.prepareStatement("SELECT appointments.message, \n" + "accounts.firstName, accounts.lastName FROM appointments INNER JOIN accounts ON appointments.accountId = accounts.accountId \n" + "WHERE appointments.departmentId = ? AND appointments.date = ?;"); pstmt.setInt(1, departmentId); pstmt.setDate(2, date); ResultSet resultSet = pstmt.executeQuery(); List<Patient> appointmentsList = new ArrayList<Patient>(); while (resultSet.next()) { Patient patient = new Patient(); patient.setPatientFirstName(resultSet.getString("firstName")); patient.setPatientSecondName(resultSet.getString("lastName")); patient.setPatientClaim(resultSet.getString("message")); appointmentsList.add(patient); } patients = new Patient[appointmentsList.size()]; patients = appointmentsList.toArray(patients); pstmt.close(); } catch (NamingException ex) { Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(AppointmentController.class.getName()).log(Level.SEVERE, null, ex); } return patients; }
From source file:org.fornax.cartridges.sculptor.framework.util.db.DatabaseExport.java
public Connection getConnection() throws SQLException { DataSource ds = (DataSource) context.getBean(environmentStrategy.getDatasourceName()); return ds.getConnection(); }
From source file:de.iritgo.aktario.jdbc.DeleteUser.java
/** * Perform the command.//from w ww . ja v a2s.c om */ public void perform() { if (properties.get("id") == null) { Log.logError("persist", "DeleteUser", "Missing unique id for the user to delete"); return; } UserRegistry userRegistry = Server.instance().getUserRegistry(); long userId = ((Long) properties.get("id")).longValue(); User user = userRegistry.getUser(userId); if (user == null) { Log.logError("persist", "DeleteUser", "Unable to find user with id " + userId); return; } JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager"); DataSource dataSource = jdbcManager.getDefaultDataSource(); Connection connection = null; PreparedStatement stmt = null; try { connection = dataSource.getConnection(); stmt = connection.prepareStatement("delete from IritgoUser where id=?"); stmt.setLong(1, userId); stmt.execute(); stmt.close(); stmt = connection.prepareStatement("delete from IritgoNamedObjects where userId=?"); stmt.setLong(1, userId); stmt.execute(); stmt.close(); Log.logVerbose("persist", "DeleteUser", "DELETE USER " + userId); } catch (SQLException x) { Log.logError("persist", "DeleteUser", "Error while storing user with id " + userId + ": " + x); } finally { DbUtils.closeQuietly(stmt); DbUtils.closeQuietly(connection); } }
From source file:de.langmi.spring.batch.examples.readers.support.CompositeCursorItemReaderTest.java
/** * Properly tears down a HSQLDB in-memory database. * * @param dataSource//from ww w . j a v a 2 s . co m * @throws Exception */ private void tearDownDataSource(final DataSource dataSource) throws Exception { Connection conn = dataSource.getConnection(); Statement st = conn.createStatement(); st.execute("SHUTDOWN"); conn.commit(); st.close(); }
From source file:azkaban.db.DatabaseOperatorTest.java
@Before public void setUp() throws Exception { this.queryRunner = mock(QueryRunner.class); this.conn = this.datasource.getConnection(); final DataSource mockDataSource = mock(this.datasource.getClass()); when(this.queryRunner.getDataSource()).thenReturn(mockDataSource); when(mockDataSource.getConnection()).thenReturn(this.conn); this.dbOperator = new DatabaseOperator(this.queryRunner); list.add(index_1);//from w w w. j a va2s . co m list.add(index_2); // valid query returns correct value when(this.queryRunner.query("select * from blah where ? = ?", this.handler, "id", 2)).thenReturn(index_2); // If select an non-existing entry, handler returns 0. when(this.queryRunner.query("select * from blah where ? = ?", this.handler, "id", 3)).thenReturn(0); //If typos, throw Exceptions. doThrow(SQLException.class).when(this.queryRunner).query("sele * from blah where ? = ?", this.handler, "id", 2); doAnswer(invocation -> { index_1 = 26; return 1; }).when(this.queryRunner).update("update blah set ? = ?", "1", 26); }
From source file:com.gs.obevo.db.scenariotests.MultiEnvDeployScenarioTest.java
private void validateInstance(String instanceName, String schemaName) throws Exception { DataSource ds = JdbcDataSourceFactory.createFromJdbcUrl(org.h2.Driver.class, H2JdbcDataSourceFactory.getUrl(instanceName, false), new Credential("sa", "")); JdbcHelper jdbc = new JdbcHelper(); Connection conn = ds.getConnection(); try {//ww w . ja va 2 s . co m int count = jdbc.queryForInt(conn, "select count(*) from " + schemaName + ".TABLE_A where 1=0"); assertEquals("Expecting a successful return for " + instanceName + " and schemaName as the table should exist", 0, count); } finally { DbUtils.closeQuietly(conn); } }
From source file:org.cloudfoundry.identity.uaa.codestore.ExpiringCodeStoreTests.java
@Test public void testDatabaseDown() throws Exception { if (JdbcExpiringCodeStore.class == expiringCodeStoreClass) { javax.sql.DataSource ds = mock(javax.sql.DataSource.class); when(ds.getConnection()).thenThrow(new SQLException()); ((JdbcExpiringCodeStore) expiringCodeStore).setDataSource(ds); try {/*w w w .j a v a 2 s . c o m*/ String data = "{}"; Timestamp expiresAt = new Timestamp(System.currentTimeMillis() + 10000000); ExpiringCode generatedCode = expiringCodeStore.generateCode(data, expiresAt); fail("Database is down, should not generate a code"); } catch (DataAccessException x) { } } }
From source file:com.gs.obevo.db.scenariotests.MigrationScenarioTest.java
private void validateInstance(String instanceName, String schemaName) throws Exception { DataSource ds = JdbcDataSourceFactory.createFromJdbcUrl(org.h2.Driver.class, H2JdbcDataSourceFactory.getUrl(instanceName, false), new Credential("sa", "")); JdbcHelper jdbc = new JdbcHelper(); Connection conn = ds.getConnection(); try {/*from w w w . j av a 2 s .c om*/ int count = jdbc.queryForInt(conn, "select count(*) from " + schemaName + ".TABLE_A"); assertEquals(6, count); // TODO verify the timestamp and ordering of rows in the table? } finally { DbUtils.closeQuietly(conn); } }
From source file:name.marcelomorales.siqisiqi.bonecp.DataSourceProviderTest.java
@Test public void testStatistics() throws Exception { Config config = ConfigFactory.parseString("bonecp.url=\"jdbc:derby:memory:dbstats;create=true\"") .withFallback(ConfigFactory.load()); DataSourceProvider dsp = new DataSourceProvider(config); assertNull(dsp.getStatistics());//w ww. j a va 2s . c om DataSource dataSource = dsp.get(); Connection connection = dataSource.getConnection(); connection.createStatement().execute("CREATE TABLE TABLETEST1 (ACOLUMN VARCHAR(10))"); connection.commit(); QueryRunner queryRunner = new QueryRunner(); queryRunner.update(connection, "INSERT INTO TABLETEST1 VALUES ('AAA')"); queryRunner.update(connection, "INSERT INTO TABLETEST1 VALUES (?)", "BBB"); queryRunner.update(connection, "INSERT INTO TABLETEST1 VALUES (?)", "CCC"); connection.commit(); List<String> values = queryRunner.query(connection, "SELECT * FROM TABLETEST1 ORDER BY ACOLUMN ASC", new ColumnListHandler<String>()); connection.commit(); connection.close(); assertEquals("AAA", values.get(0)); assertEquals("BBB", values.get(1)); assertEquals("CCC", values.get(2)); Statistics statistics = dsp.getStatistics(); assertTrue(statistics.getCacheHits() > 0); assertTrue(statistics.getCacheMiss() > 0); assertEquals(1, statistics.getConnectionsRequested()); assertEquals(4, statistics.getStatementsPrepared()); dsp.close(); }
From source file:com.p6spy.engine.spy.MultipleDataSourceTest.java
private void validateSpyEnabled(DataSource ds) throws SQLException { assertNotNull("JNDI data source not found", ds); // get the connection Connection con = ds.getConnection(); // verify that the connection class is a proxy assertTrue("Connection is not a proxy", ProxyFactory.isProxy(con.getClass())); if (con.getMetaData().getDatabaseProductName().contains("HSQL")) { con.createStatement().execute("set database sql syntax ora true"); }/*w w w . j av a2 s . c o m*/ con.createStatement().execute("select current_date from dual"); assertTrue(((P6TestLogger) P6LogQuery.getLogger()).getLastEntry().indexOf("select current_date") != -1); }