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:de.highbyte_le.weberknecht.db.DefaultWebDbConnectionProvider.java
public Connection getConnection() throws DBConnectionException { try {/*from w w w.ja va 2 s. c o m*/ //JNDI-Context Context ctx = new InitialContext(); Context envCtx = (Context) ctx.lookup("java:comp/env"); //JNDI-Lookup for jdbc connection DataSource ds = (DataSource) envCtx.lookup("jdbc/mydb"); Connection con = ds.getConnection(); return con; } catch (NamingException e) { logger.error("NamingException: " + e.getMessage(), e); throw new DBConnectionException("database connection is not yet configured (naming exception)", e); } catch (SQLException e) { logger.error("SQLException: " + e.getMessage(), e); throw new DBConnectionException("cannot connect to database (sql exception)", e); } }
From source file:com.taobao.ad.es.common.datasource.DataSourceFactory.java
public Connection getConnection(String contextPath, int dsType, String dataSource) throws BeansException, SQLException, NamingException { Connection connection = null; switch (dsType) { case JobData.JOBDATA_DATA_DATASOURCE_TYPE_DYNAMIC: // BeanFactoryLocator sysCtxLocator = // SingletonBeanFactoryLocator.getInstance(WebAgentConstants.DATASOURCE_CONTEXT); // BeanFactoryReference brf = // sysCtxLocator.useBeanFactory(WebAgentConstants.DATASOURCE_CONTEXT_KEY); // connection = ((DataSource) // brf.getFactory().getBean(dataSource)).getConnection(); AbstractXmlApplicationContext context = null; if (StringUtils.isEmpty(contextPath)) { context = new ClassPathXmlApplicationContext("classpath:es-agent-ds.xml"); } else {//from w w w .j a va2s.c om context = new FileSystemXmlApplicationContext(contextPath); } connection = ((DataSource) context.getBean(dataSource)).getConnection(); break; default: Context cxt = new InitialContext(); Context envCtx = (Context) cxt.lookup("java:comp/env"); DataSource ds = (DataSource) envCtx.lookup("jdbc/" + dataSource); connection = ds.getConnection(); break; } return connection; }
From source file:org.flywaydb.test.sample.helper.BaseDBHelper.java
/** * Open a connection to database for test execution statements * /* w w w .j a v a 2 s. co m*/ * @throws Exception */ @Before public void setup() throws Exception { DataSource ds = (DataSource) context.getBean("dataSourceRef"); con = ds.getConnection(); }
From source file:com.taobao.tanggong.H2ServerTest.java
@Test public void test() { H2Server h = (H2Server) this.appContext.getBean("h2Server"); DataSource dataSource = (DataSource) this.appContext.getBean("dataSource"); try {//www . j a v a2s . c o m Assert.assertNotNull(dataSource.getConnection()); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { Thread.sleep(1000000l); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.teradata.benchto.driver.jdbc.MultipleDataSourcesTest.java
private void testDataSourceAvailable(String dataSourceName) throws SQLException { DataSource dataSource = applicationContext.getBean(dataSourceName, DataSource.class); try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(SQL_TEST_STATEMENT)) { int rowsCount = 0; while (resultSet.next()) { rowsCount++;/*from w w w . j av a2 s. c o m*/ } assertThat(rowsCount).isEqualTo(1); } }
From source file:scriptella.driver.spring.SpringDriverTest.java
public void test() throws SQLException, ClassNotFoundException, EtlExecutorException { BeanFactory bf = new ClassPathXmlApplicationContext("scriptella/driver/spring/springbeans.xml"); DataSource ds = (DataSource) bf.getBean("datasource"); //Test if bean factory contain correct data Connection con = ds.getConnection(); con.createStatement().executeQuery("select * from AutoStart"); //A table should be created on startup EtlExecutor exec = (EtlExecutor) bf.getBean("executor"); exec.execute();//from ww w . j a va2 s . com con.createStatement().executeQuery("select * from SpringTable"); //A table should be created //Test batched executor ResultSet rs = con.createStatement().executeQuery("select * from Batch order by id");//A table should be created assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); con.createStatement().execute("SHUTDOWN"); }
From source file:scriptella.driver.spring.Driver.java
@Override protected java.sql.Connection getConnection(String url, Properties props) throws SQLException { if (url == null) { throw new SpringProviderException( "Name of the spring bean must be specified in an url attribute of connection element."); }/*from www .j a v a 2 s .c o m*/ try { BeanFactory beanFactory = EtlExecutorBean.getContextBeanFactory(); DataSource ds = (DataSource) beanFactory.getBean(StringUtils.removePrefix(url, "spring:")); return ds.getConnection(); } catch (Exception e) { throw new SpringProviderException( "A problem occured while trying to lookup a datasource with name " + url, e); } }
From source file:org.apache.sling.extensions.datasource.DataSourceIT.java
@Test public void testDataSourceAsService() throws Exception { Configuration config = ca.createFactoryConfiguration(PID, null); Dictionary<String, Object> p = new Hashtable<String, Object>(); p.put("url", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); p.put("datasource.name", "test"); p.put("maxActive", 70); config.update(p);//ww w. j av a 2 s . c o m Filter filter = context.createFilter("(&(objectclass=javax.sql.DataSource)(datasource.name=test))"); ServiceTracker<DataSource, DataSource> st = new ServiceTracker<DataSource, DataSource>(context, filter, null); st.open(); DataSource ds = st.waitForService(10000); assertNotNull(ds); Connection conn = ds.getConnection(); assertNotNull(conn); //Cannot access directly so access via reflection assertEquals("70", getProperty(ds, "poolProperties.maxActive")); }
From source file:example.unittest.ExampleDbUnitTest.java
private void loadData(DataSource ds) { try (Connection connection = ds.getConnection()) { JdbcHelper jdbc = new JdbcHelper(); jdbc.update(connection, "INSERT INTO DEMO_SCHEMA.DYN_TABLE_D (D_ID) VALUES (1)"); jdbc.update(connection, "INSERT INTO DEMO_SCHEMA.DYN_TABLE_D (D_ID) VALUES (2)"); jdbc.update(connection, "INSERT INTO DEMO_SCHEMA.DYN_TABLE_D (D_ID) VALUES (3)"); jdbc.update(connection,// w w w . j a v a 2s . c o m "INSERT INTO DEMO_SCHEMA.DYN_TABLE_C (C_ID,D_ID,STRING_FIELD,TIMESTAMP_FIELD) VALUES (1,1,'row1',null)"); jdbc.update(connection, "INSERT INTO DEMO_SCHEMA.DYN_TABLE_C (C_ID,D_ID,STRING_FIELD,TIMESTAMP_FIELD) VALUES (2,2,'row 2','2013-01-02 12:34:56')"); jdbc.update(connection, "INSERT INTO DEMO_SCHEMA.DYN_TABLE_C (C_ID,D_ID,STRING_FIELD,TIMESTAMP_FIELD) VALUES (3,2,'','2013-01-02 12:34:56.1')"); jdbc.update(connection, "INSERT INTO DEMO_SCHEMA.DYN_TABLE_C (C_ID,D_ID,STRING_FIELD,TIMESTAMP_FIELD) VALUES (4,2,' row 4 ','2013-01-02 12:34:56.234')"); jdbc.update(connection, "INSERT INTO DEMO_SCHEMA.DYN_TABLE_C (C_ID,D_ID,STRING_FIELD,TIMESTAMP_FIELD) VALUES (5,2,null,'2013-01-02 12:34:56.567891')"); } catch (SQLException e) { throw new RuntimeException(e); } }
From source file:com.googlecode.datasourcetester.server.DataSourceTesterServiceImpl.java
public String[][] queryDataSource(String dataSourceJndiName, String query) { Connection conn = null;//from w w w . jav a 2s. c om try { InitialContext jndiContext = new InitialContext(); DataSource ds = (DataSource) jndiContext.lookup(dataSourceJndiName); conn = ds.getConnection(); PreparedStatement stmt = conn.prepareStatement(query); ResultSet rs = stmt.executeQuery(); ResultSetMetaData resMeta = rs.getMetaData(); LinkedList<String[]> rowList = new LinkedList<String[]>(); String[] colLabels = new String[resMeta.getColumnCount()]; for (int colNr = 1; colNr <= resMeta.getColumnCount(); colNr++) { colLabels[colNr - 1] = resMeta.getColumnName(colNr); } rowList.add(colLabels); while (rs.next()) { String[] rowData = new String[resMeta.getColumnCount()]; for (int colNr = 1; colNr <= resMeta.getColumnCount(); colNr++) { rowData[colNr - 1] = rs.getString(colNr); } rowList.add(rowData); } conn.close(); return rowList.toArray(new String[rowList.size()][]); } catch (Exception e) { logger.error(e.getMessage(), e); try { if (conn != null && !conn.isClosed()) { conn.close(); } } catch (SQLException sqlEx) { logger.error(sqlEx.getMessage(), sqlEx); } return null; } }