private boolean validateSQL(JobVO jobVO) { SingleConnectionDataSource ds = new SingleConnectionDataSource(); try { ds.setDriverClassName(jobVO.getDriverClassName()); ds.setUrl(jobVO.getUrl()); ds.setUsername(jobVO.getUsername()); ds.setPassword(jobVO.getPassword()); JdbcTemplate template = new JdbcTemplate(ds); template.execute(jobVO.getSql()); return true; } catch (Throwable t) { return false; } finally { ds.destroy(); } }
@Test public void testLeaveConnectionOpenOnRequest() throws Exception { String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3"; given(this.resultSet.next()).willReturn(false); given(this.connection.isClosed()).willReturn(false); given(this.connection.createStatement()).willReturn(this.preparedStatement); // if close is called entire test will fail willThrow(new RuntimeException()).given(this.connection).close(); SingleConnectionDataSource scf = new SingleConnectionDataSource(this.dataSource.getConnection(), false); this.template = new JdbcTemplate(scf, false); RowCountCallbackHandler rcch = new RowCountCallbackHandler(); this.template.query(sql, rcch); verify(this.resultSet).close(); verify(this.preparedStatement).close(); }
public String executeSql(String sql,String code) throws Exception { SingleConnectionDataSource ds = getSingleConnectionDataSource(code); this.setRtJdbcTemplate(ds); String result; try { result = (String)this.rtJdbcTemplate.queryForObject(sql,null,java.lang.String.class); return result; } catch (Exception e) { log.error(this.getClass() + "\n---方法:" + new Exception().getStackTrace()[0].getMethodName() + "\n---e.getMessage():\n" + e.toString() + "\n" + e); throw new Exception(e.getMessage()); } finally{ ds.getConnection().close(); } }
public SingleConnectionDataSource getSingleConnectionDataSource(String code) throws Exception { //String sql ="select t2.DRIVER_CLASS as driver,t2.url ,t2.user_name ,t2.password from SYS_DATA_SOURCE t1,sys_db_links t2 where t1.link_id=t2.link_id and t1.code='"+code+"'"; String sql ="select t2.DRIVER_CLASS as driver,t2.url ,t2.user_name ,t2.password from SYS_DATA_SOURCE t1,sys_db_links t2 where t1.link_id=t2.link_id and t1.sh_code='"+code+"'"; List<Map<String,Object>> list = (List<Map<String,Object>>)this.jdbcTemplate.queryForList(sql); Map<String,Object> map = new HashMap<String,Object>(); if(list.size()>0){ map = list.get(0); } SingleConnectionDataSource ds = new SingleConnectionDataSource(); ds.setDriverClassName(ParseUtil.getString(map.get("driver"))); ds.setUrl(ParseUtil.getString(map.get("url"))); ds.setUsername(ParseUtil.getString(map.get("user_name"))); ds.setPassword(ParseUtil.getString(map.get("password"))); return ds; }
@Override public NonceVerifier createVerifier(int maxAge) { DataSource dataSource = new SingleConnectionDataSource( "org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:saasstore_security_client", "sa", "", true); SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(dataSource); jdbcTemplate.getJdbcOperations().execute( "DROP TABLE IF EXISTS openid_nonce;"); jdbcTemplate .getJdbcOperations() .execute( "CREATE TABLE openid_nonce ( " + "opurl varchar(255) NOT NULL, nonce varchar(25) NOT NULL, " + "date datetime DEFAULT NULL, PRIMARY KEY (opurl,nonce))"); JdbcNonceVerifier jdbcNonceVerifier = new JdbcNonceVerifier(maxAge, "openid_nonce"); jdbcNonceVerifier.setDataSource(dataSource); return jdbcNonceVerifier; }
@Test @DirtiesContext public void addAndGet() throws SQLException { DataSource dataSource = new SingleConnectionDataSource( "jdbc:mysql://54.64.47.206/mykumitestdb","dbuser", "dbuser1*",true); jdbcContext.setDataSource(dataSource); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); userDao.setJdbcTemplate(jdbcTemplate); userDao.deleteAll(); assertThat(userDao.getCount(), is(0)); User user = new User("u1", "user01", "111111", Level.BASIC,1,0); userDao.add(user); assertThat(userDao.getCount(), is(1)); User user2 = userDao.get(user.getId()); assertThat(user.getName(), is(user2.getName())); assertThat(user.getPassword(), is(user2.getPassword())); }
private void applyScripts(String url) throws SQLException, IOException { log.info("Apply Scripts ..."); Connection connection = getConnection(url); DataSource ds = new SingleConnectionDataSource(connection, false); FileSystemScanner scanner = new FileSystemScanner(); for (String location : builder.locations) { File directory = new File(location); if (directory.exists() && directory.isDirectory()) { Resource[] resources = scanner.scanForResources(location, "", ".sql"); ResourceDatabasePopulator populator = new ResourceDatabasePopulator(resources); populator.setSeparator(builder.separator); populator.execute(ds); } else { // log not existing directory } } log.info("Scripts applied!"); }
@Test public void testSql2O() throws SQLException, ParseException { Connection connection = DbHelper.objectDb(); try { SingleConnectionDataSource scds = new SingleConnectionDataSource(connection, true); Sql2o sql2o = new Sql2o(scds); Query query = sql2o.open().createQuery(DbHelper.TEST_DB_OBJECT_QUERY); query.setAutoDeriveColumnNames(true); query.setResultSetHandlerFactoryBuilder(new SfmResultSetHandlerFactoryBuilder()); List<DbObject> dbObjects = query.executeAndFetch(DbObject.class); assertEquals(1, dbObjects.size()); DbHelper.assertDbObjectMapping(dbObjects.get(0)); } finally { connection.close(); } }
@Before public void setUp() throws SQLException { connection = mock(Connection.class); statement = mock(Statement.class); preparedStatement = mock(PreparedStatement.class); resultSet = mock(ResultSet.class); given(connection.createStatement()).willReturn(statement); given(connection.prepareStatement(anyString())).willReturn(preparedStatement); given(statement.executeQuery(anyString())).willReturn(resultSet); given(preparedStatement.executeQuery()).willReturn(resultSet); given(resultSet.next()).willReturn(true, true, false); given(resultSet.getString(1)).willReturn("tb1", "tb2"); given(resultSet.getInt(2)).willReturn(1, 2); template = new JdbcTemplate(); template.setDataSource(new SingleConnectionDataSource(connection, false)); template.setExceptionTranslator(new SQLStateSQLExceptionTranslator()); template.afterPropertiesSet(); }
private void updateCurrentChunk() { if (logger.isDebugEnabled()) { logger.debug("Updating HILO chunk..."); } long t = System.currentTimeMillis(); try (Connection conn = dataSource.getConnection()) { conn.setAutoCommit(false); JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(conn, true)); jdbcTemplate.update(SQL_LOCK); currentChunk = jdbcTemplate.queryForObject(SQL_SELECT, Integer.class); if (logger.isDebugEnabled()) logger.debug("Current chunk: " + currentChunk); jdbcTemplate.execute(SQL_UPDATE); jdbcTemplate.execute("commit"); if (logger.isDebugEnabled()) { logger.debug("Updating HILO chunk done in " + (System.currentTimeMillis() - t) + " ms"); } currentId = 0; } catch (SQLException e) { logger.error("Unable to update current chunk", e); throw new IllegalStateException("Unable to update current chunk"); } }
private Set<Utilization> findLatestUtilizationPostgreSQL(Long[] facilityIds, SingleConnectionDataSource dataSource) { NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource); return new LinkedHashSet<>(jdbcTemplate.query("" + "SELECT latest.* " + "FROM (" + " SELECT DISTINCT facility_id, capacity_type, usage " + " FROM pricing " + (facilityIds.length > 0 ? " WHERE facility_id IN (:facility_ids) " : "") + ") p " + "JOIN LATERAL ( " + " SELECT * " + " FROM facility_utilization " + " WHERE facility_id = p.facility_id AND capacity_type = p.capacity_type AND usage = p.usage " + " ORDER BY ts DESC " + " LIMIT 1 " + ") latest ON TRUE " + "ORDER BY facility_id, capacity_type, usage", new MapSqlParameterSource("facility_ids", Arrays.asList(facilityIds)), utilizationRowMapper)); }
public Mock(MockType type) throws Exception { connection = mock(Connection.class); statement = mock(Statement.class); resultSet = mock(ResultSet.class); resultSetMetaData = mock(ResultSetMetaData.class); given(connection.createStatement()).willReturn(statement); given(statement.executeQuery(anyString())).willReturn(resultSet); given(resultSet.getMetaData()).willReturn(resultSetMetaData); given(resultSet.next()).willReturn(true, false); given(resultSet.getString(1)).willReturn("Bubba"); given(resultSet.getLong(2)).willReturn(22L); given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L)); given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56")); given(resultSet.wasNull()).willReturn(type == MockType.TWO ? true : false); given(resultSetMetaData.getColumnCount()).willReturn(4); given(resultSetMetaData.getColumnLabel(1)).willReturn( type == MockType.THREE ? "Last Name" : "name"); given(resultSetMetaData.getColumnLabel(2)).willReturn("age"); given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date"); given(resultSetMetaData.getColumnLabel(4)).willReturn("balance"); jdbcTemplate = new JdbcTemplate(); jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false)); jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator()); jdbcTemplate.afterPropertiesSet(); }
@Before public void setUp() throws SQLException { given(connection.createStatement()).willReturn(statement); given(connection.prepareStatement(anyString())).willReturn(preparedStatement); given(statement.executeQuery(anyString())).willReturn(resultSet); given(preparedStatement.executeQuery()).willReturn(resultSet); given(resultSet.next()).willReturn(true, true, false); given(resultSet.getString(1)).willReturn("tb1", "tb2"); given(resultSet.getInt(2)).willReturn(1, 2); template.setDataSource(new SingleConnectionDataSource(connection, false)); template.setExceptionTranslator(new SQLStateSQLExceptionTranslator()); template.afterPropertiesSet(); }
@Before public void init() { EmbeddedDatabaseConnection db = EmbeddedDatabaseConnection.HSQL; this.dataSource = new SingleConnectionDataSource(db.getUrl() + ";shutdown=true", "sa", "", false); this.dataSource.setDriverClassName(db.getDriverClassName()); }
public String executeSqlForTableDs(Map<String,String> sqlmap) throws Exception{ String resultSql = sqlmap.get("resultSql"); String trStyleStr = sqlmap.get("trStyleStr"); List<String> array = ParseUtil.parseTrStyleStr(trStyleStr); StringBuilder sb = new StringBuilder(); SingleConnectionDataSource ds = getSingleConnectionDataSource(sqlmap.get("code")); this.setRtJdbcTemplate(ds); try { List<Map<String,Object>> list = (List<Map<String,Object>>)this.rtJdbcTemplate.queryForList(resultSql); if(list.size()>0){ for (Map<String, Object> map : list) { String newStr =trStyleStr; for (String str :array) { String v = map.get(str.trim())==null?"":map.get(str.trim()).toString(); newStr = newStr.replaceAll("\\[&SV,"+str+",&]",v); } sb.append(newStr); } } return sb.toString(); } catch (Exception e) { log.error(this.getClass() + "\n---方法:" + new Exception().getStackTrace()[0].getMethodName() + "\n---e.getMessage():\n" + e.toString() + "\n" + e); throw new Exception(e.getMessage()); } finally{ ds.getConnection().close(); } }
public Map<String,Object> executeSqlForForm(String sql,String code) throws Exception{ if(!ParseUtil.isNotNullforString(sql)){ throw new Exception("执行executeSqlForForm时sql为空!"); } SingleConnectionDataSource ds = getSingleConnectionDataSource(code); this.setRtJdbcTemplate(ds); try { List<Map<String,Object>> list = (List<Map<String,Object>>)this.rtJdbcTemplate.queryForList(sql); if(list.size()>0){ return list.get(0); } return null; } catch (Exception e) { log.error(this.getClass() + "\n---方法:" + new Exception().getStackTrace()[0].getMethodName() + "\n---e.getMessage():\n" + e.toString() + "\n" +e); throw new Exception(e.getMessage()); } finally{ ds.getConnection().close(); } }
/** * added by JBJ 根据任务参数设置寻找数据库连接信息 * * @param taskId * @return * @throws Exception */ public SingleConnectionDataSource getSingleConnectionDataSource(Long taskId) throws Exception { String sql = "SELECT t.param_value linkName FROM SYS_PARAM_ALL T WHERE SYSDATE BETWEEN T.ENABLE_DATE AND NVL(T.DISABLE_DATE, SYSDATE) AND t.param_name = 'DB_LINK' AND T.TASK_ID = " + taskId; List<Map<String, Object>> list = (List<Map<String, Object>>) this.jdbcTemplate .queryForList(sql); Map<String, Object> map = new HashMap<String, Object>(); if (list.size() > 0) { map = list.get(0); } String linkCode = ParseUtil.getString(map.get("linkName")); sql = "SELECT dl.dRIVER_CLASS as driver,dl.url ,dl.user_name ,dl.password FROM sys_db_links dl WHERE SYSDATE BETWEEN DL.ENABLE_DATE AND NVL(DL.DISABLE_DATE, SYSDATE) AND DL.LINK_CODE = '" + linkCode + "'"; list = (List<Map<String, Object>>) this.jdbcTemplate.queryForList(sql); map = new HashMap<String, Object>(); if (list.size() > 0) { map = list.get(0); } SingleConnectionDataSource ds = new SingleConnectionDataSource(); ds.setDriverClassName(ParseUtil.getString(map.get("driver"))); ds.setUrl(ParseUtil.getString(map.get("url"))); ds.setUsername(ParseUtil.getString(map.get("user_name"))); ds.setPassword(ParseUtil.getString(map.get("password"))); return ds; }
@Before public void setUp() throws SQLException, ClassNotFoundException { Class.forName("org.hsqldb.jdbcDriver"); Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:parfait", "sa", ""); DataSource wrapped = new SingleConnectionDataSource(c, false); dataSource = new ParfaitDataSource(wrapped); }
public HeartBeatDBSource() { try { conn = dbf.getExtraDataSource().getConnection(); source = new SingleConnectionDataSource(conn, true); jdbc = new JdbcTemplate(source); } catch (SQLException e) { throw new CloudRuntimeException(e); } }
/** * return a DataSource with a single underlying connection. * this allow a user to perform multiple tasks on one connection. * this implementation is not thread-safe. * @param dbInstance * @return */ public static DataSource getSingleConnectionDS(DbInstance dbInstance) { try { return new SingleConnectionDataSource(getDataSource(dbInstance).getConnection(), false); } catch (SQLException e) { logger.error(e); } return null; }
@Before public void setUp() throws SQLException { Connection dbConnection; try { dbConnection = DbHelper.getDbConnection(DbHelper.TargetDB.MYSQL); dbConnection.createStatement().executeQuery("SELECT 1"); } catch(Exception e) { dbConnection = DbHelper.getDbConnection(DbHelper.TargetDB.HSQLDB); } template = new JdbcTemplate(new SingleConnectionDataSource(dbConnection, true)); }
@TransactionalRead @Override public Set<Utilization> findLatestUtilization(Long... facilityIds) { Connection connection = queryFactory.getConnection(); if (isPostgreSQL(connection)) { return findLatestUtilizationPostgreSQL(facilityIds, new SingleConnectionDataSource(connection, true)); } else { return findLatestUtilizationH2(facilityIds); } }
protected JdbcTemplate createJdbcTemplate(Connection conn) { try { return new JdbcTemplate(new SingleConnectionDataSource(conn, true)); } catch (Exception e) { throw e instanceof IdException ? (IdException) e : new IdException(e); } }
/** * Read properties and instantiate ApplicationContext */ protected void initialize() { try { Properties properties = new Properties(); properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTIES_FILE)); this.localContextFactory = properties.getProperty("local.context.factory"); this.localHost = properties.getProperty("local.host"); this.localPort = Integer.parseInt(properties.getProperty("local.port")); this.localProviderUrl = properties.getProperty("local.provider.url"); this.fdbDifJdbcUrl = properties.getProperty("local.fdb.dif.jdbc.url"); this.fdbDifUser = properties.getProperty("local.fdb.dif.user"); this.fdbDifPassword = properties.getProperty("local.fdb.dif.password"); this.fdbDifDriver = properties.getProperty("local.fdb.dif.driver"); this.datupJdbcUrl = properties.getProperty("national.datup.jdbc.url"); this.datupUser = properties.getProperty("national.datup.user"); this.datupPassword = properties.getProperty("national.datup.password"); this.datupDriver = properties.getProperty("national.datup.driver"); // Register the JDBC driver and load the data source Class.forName(getFdbDifDriver()).newInstance(); this.fdbDifDataSource = new SingleConnectionDataSource(getFdbDifJdbcUrl(), getFdbDifUser(), getFdbDifPassword(), true); this.fdbDifJdbcTemplate = new JdbcTemplate(fdbDifDataSource); Class.forName(getDatupDriver()).newInstance(); this.datupDataSource = new SingleConnectionDataSource(getDatupJdbcUrl(), getDatupUser(), getDatupPassword(), true); this.datupJdbcTemplate = new JdbcTemplate(datupDataSource); national.providerUrl = properties.getProperty("national.provider.url"); national.contextFactory = properties.getProperty("national.context.factory"); } catch (Exception e) { throw new RuntimeException(e); // NOPMD - we're in a test case anyway } }
public void doMain(String argv[]) throws Exception { String url = "jdbc:derby:target/x;create=true"; Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); DataSource dataSource = new SingleConnectionDataSource(url, null, null, false); Connection connection = null; try { connection = dataSource.getConnection(); readCommands(connection); } finally { if (connection != null) { connection.close(); } } }
@Bean public DataSource dataSource() throws SQLException { SingleConnectionDataSource ds = new SingleConnectionDataSource( this.env.getProperty("db.url"), this.env.getProperty("db.username"), this.env.getProperty("db.password"), this.env.getProperty("db.defaultAutoCommit", Boolean.class)); ds.setAutoCommit(false); return ds; }
public void buildFields(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String sql=req.getParameter("sql"); String parameters=req.getParameter("parameters"); Connection conn=null; final List<Field> fields=new ArrayList<Field>(); try{ conn=buildConnection(req); Map<String, Object> map = buildParameters(parameters); sql=parseSql(sql, map); if(ProcedureUtils.isProcedure(sql)){ List<Field> fieldsList = ProcedureUtils.procedureColumnsQuery(sql, map, conn); fields.addAll(fieldsList); }else{ DataSource dataSource=new SingleConnectionDataSource(conn,false); NamedParameterJdbcTemplate jdbc=new NamedParameterJdbcTemplate(dataSource); PreparedStatementCreator statementCreator=getPreparedStatementCreator(sql,new MapSqlParameterSource(map)); jdbc.getJdbcOperations().execute(statementCreator, new PreparedStatementCallback<Object>() { @Override public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { ResultSet rs = null; try { rs = ps.executeQuery(); ResultSetMetaData metadata=rs.getMetaData(); int columnCount=metadata.getColumnCount(); for(int i=0;i<columnCount;i++){ String columnName=metadata.getColumnLabel(i+1); fields.add(new Field(columnName)); } return null; }finally { JdbcUtils.closeResultSet(rs); } } }); } writeObjectToJson(resp, fields); }catch(Exception ex){ throw new ReportDesignException(ex); }finally{ JdbcUtils.closeConnection(conn); } }
public void previewData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String sql=req.getParameter("sql"); String parameters=req.getParameter("parameters"); Map<String, Object> map = buildParameters(parameters); sql=parseSql(sql, map); Connection conn=null; try{ conn=buildConnection(req); List<Map<String,Object>> list=null; if(ProcedureUtils.isProcedure(sql)){ list=ProcedureUtils.procedureQuery(sql, map, conn); }else{ DataSource dataSource=new SingleConnectionDataSource(conn,false); NamedParameterJdbcTemplate jdbc=new NamedParameterJdbcTemplate(dataSource); list=jdbc.queryForList(sql, map); } int size=list.size(); int currentTotal=size; if(currentTotal>500){ currentTotal=500; } List<Map<String,Object>> ls=new ArrayList<Map<String,Object>>(); for(int i=0;i<currentTotal;i++){ ls.add(list.get(i)); } DataResult result=new DataResult(); List<String> fields=new ArrayList<String>(); if(size>0){ Map<String,Object> item=list.get(0); for(String name:item.keySet()){ fields.add(name); } } result.setFields(fields); result.setCurrentTotal(currentTotal); result.setData(ls); result.setTotal(size); writeObjectToJson(resp, result); }catch(Exception ex){ throw new ServletException(ex); }finally{ if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
public static SingleConnectionDataSource getDataSourceFrom(String databaseFile) { SingleConnectionDataSource dataSource = new SingleConnectionDataSource(); dataSource.setDriverClassName("org.sqlite.JDBC"); dataSource.setUrl("jdbc:sqlite:" + databaseFile); return dataSource; }
public static SingleConnectionDataSource getDataSourceFrom(File directory) { return getDataSourceFrom(getDatabasePath(directory)); }
public JdbcSlimRunner(final String driverClassname, final String url, final String username, final String password, final String sql) throws ClassNotFoundException { Class.forName(driverClassname); this.template = new JdbcTemplate(new SingleConnectionDataSource(url, username, password, false)); this.sql = sql; }
@Bean public DataSource dataSource() { return new SingleConnectionDataSource("jdbc:hsqldb:mem:.", "sa", "", true); }
public void setRtJdbcTemplate(SingleConnectionDataSource ds) { this.rtJdbcTemplate = new JdbcTemplate(ds); }
public List<ImageDefData> executeSqlForImgdefDs(Map<String,String> sqlmap)throws Exception{ String resultSql = sqlmap.get("resultSql"); String showViewStr = sqlmap.get("showViewStr"); List<ImageDefData> returnList = new ArrayList<ImageDefData>(); SingleConnectionDataSource ds = getSingleConnectionDataSource(sqlmap.get("code")); this.setRtJdbcTemplate(ds); try { List<Map<String,Object>> list = (List<Map<String,Object>>)this.rtJdbcTemplate.queryForList(resultSql); if(list.size()>0){ for (Map<String, Object> map : list) { ImageDefData imageDefData = new ImageDefData(); String [] array = showViewStr.split("&"); for (String str : array) { String [] arrP =str.split("="); if(arrP.length==1) { imageDefData = this.getImageDefData(imageDefData, arrP[0], ""); } else { imageDefData = this.getImageDefData(imageDefData, arrP[0], ParseUtil.getString(map.get(arrP[1]))); } } returnList.add(imageDefData); } } return returnList; } catch (Exception e) { log.error(this.getClass() + "\n---方法:" + new Exception().getStackTrace()[0].getMethodName() + "\n---e.getMessage():\n" + e.toString() + "\n" +e); throw new Exception(e.getMessage()); } finally{ ds.getConnection().close(); } }
protected JdbcTemplate getJdbcTemplate(Connection connection) { DataSource dataSource = new SingleConnectionDataSource(connection, true); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return jdbcTemplate; }