当前位置: 首页>>代码示例>>Java>>正文


Java DataSourceUtils类代码示例

本文整理汇总了Java中org.springframework.jdbc.datasource.DataSourceUtils的典型用法代码示例。如果您正苦于以下问题:Java DataSourceUtils类的具体用法?Java DataSourceUtils怎么用?Java DataSourceUtils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


DataSourceUtils类属于org.springframework.jdbc.datasource包,在下文中一共展示了DataSourceUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: writeExecuteFlag

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
@Override
public void writeExecuteFlag(String appId, String busCode, String trxId, String pAppId, String pBusCode, String pTrxId, int status) {
	
	Connection connection = DataSourceUtils.getConnection(selctor.selectDataSource(appId, busCode, trxId));
	
	try {
		PreparedStatement prepareStatement = connection.prepareStatement("INSERT INTO `executed_trans` (`app_id`, `bus_code`, `trx_id`,`p_app_id`, `p_bus_code`, `p_trx_id`,`status`) VALUES ( ?, ?, ?, ?, ?, ?, ?);");
		prepareStatement.setString(1, appId);
		prepareStatement.setString(2, busCode);
		prepareStatement.setString(3, trxId);
		prepareStatement.setString(4, pAppId);
		prepareStatement.setString(5, pBusCode);
		prepareStatement.setString(6, pTrxId);
		prepareStatement.setInt(7, status);
		
		int executeUpdate = prepareStatement.executeUpdate();
		if(executeUpdate != 1){
			throw new RuntimeException(String.format("insert count(%s) Error!%s %s %s %s %s %s %s", executeUpdate,appId,busCode,trxId,pAppId,pBusCode,pTrxId,status));
		}
	} catch (SQLException e) {
		throw new RuntimeException("insert Sql failed,check whether the same transaction has been executed?",e);
	}
}
 
开发者ID:QNJR-GROUP,项目名称:EasyTransaction,代码行数:24,代码来源:DefaultTransStatusLoggerImpl.java

示例2: updateExecuteFlagForSlaveTrx

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
@Override
public void updateExecuteFlagForSlaveTrx(TransactionId pId, EasyTransRequest<?, ?> request, int status) {
	
	BusinessIdentifer businessIdentifer = request.getClass().getAnnotation(BusinessIdentifer.class);
	
	Connection connection = DataSourceUtils.getConnection(selctor.selectDataSource(businessIdentifer.appId(),businessIdentifer.busCode(),request));
	
	try {
		PreparedStatement prepareStatement = connection.prepareStatement("UPDATE `executed_trans` SET `status` =  ? WHERE  `p_app_id` =  ? AND `p_bus_code` =  ? AND `p_trx_id` = ?;");
		prepareStatement.setInt(1, status);
		prepareStatement.setString(2, pId.getAppId());
		prepareStatement.setString(3, pId.getBusCode());
		prepareStatement.setString(4, pId.getTrxId());
		prepareStatement.executeUpdate();
	} catch (SQLException e) {
		throw new RuntimeException("updateExecuteFlagForSlaveTrx failed ",e);
	}
}
 
开发者ID:QNJR-GROUP,项目名称:EasyTransaction,代码行数:19,代码来源:DefaultTransStatusLoggerImpl.java

示例3: checkAbnormalSlaves

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
/**
 * 自动上线可用数据源<br/>
 * 检查AbnormalSlaves,如果正常则丢回normalSlaves 
 */
protected void checkAbnormalSlaves(){
	//循环检查所有的失效从库数据源
	for(int i = 0; i < abnormalSlaves.size();i++){ 
		DataSource ds = null;
		Connection conn = null;
		try {
			ds = abnormalSlaves.get(i);
			//step检测可连接性
			String ipAndPort = getMapKey(ds);
			if(ConnUtil.isReachable(ipAndPort, validationQueryTimeout)){
				//step:  数据库直连检测
				conn = ds.getConnection(); 
				validateSlaveStatus(conn);
				online(ds);
			}
			break;
		} catch (Throwable e) { 
			continue;
		}finally{
			if(conn != null && ds != null) DataSourceUtils.releaseConnection(conn, ds);
		} 
	}
}
 
开发者ID:w775450,项目名称:DynamicDataSource,代码行数:28,代码来源:DynamicMysqlDataSource.java

示例4: checkNormalSlaves

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
/**
 * 自动下线无效数据源<br/>
 * 检查snormalSlaves,如果不正常则丢到AbnormalSlave
 */
protected void checkNormalSlaves(){
	//循环检查所有的失效从库数据源
	for(int i = 0; i < normalSlaves.size();i++){
		DataSource ds = null;
		Connection conn = null;
		try {
			ds = normalSlaves.get(i);
			//step检测可连接性
			String ipAndPort = getMapKey(ds);
			if(!ConnUtil.isReachable(ipAndPort, validationQueryTimeout)){
				throw new Exception("不能连接到"+ipAndPort);
			}
			conn = ds.getConnection();
			validateSlaveStatus(conn);
		} catch (Throwable e) {
			logger.error("数据源检查线程发现不可用的数据源",e);
			offline(ds,e.getMessage());
			break;
		}finally{
			if(conn != null && ds != null) DataSourceUtils.releaseConnection(conn, ds);
		} 
	}
}
 
开发者ID:w775450,项目名称:DynamicDataSource,代码行数:28,代码来源:DynamicMysqlDataSource.java

示例5: execute

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
/**
 * Execute the given {@link DatabasePopulator} against the given {@link DataSource}.
 * @param populator the {@code DatabasePopulator} to execute
 * @param dataSource the {@code DataSource} to execute against
 * @throws DataAccessException if an error occurs, specifically a {@link ScriptException}
 */
public static void execute(DatabasePopulator populator, DataSource dataSource) throws DataAccessException {
	Assert.notNull(populator, "DatabasePopulator must be provided");
	Assert.notNull(dataSource, "DataSource must be provided");
	try {
		Connection connection = DataSourceUtils.getConnection(dataSource);
		try {
			populator.populate(connection);
		}
		finally {
			if (connection != null) {
				DataSourceUtils.releaseConnection(connection, dataSource);
			}
		}
	}
	catch (Exception ex) {
		if (ex instanceof ScriptException) {
			throw (ScriptException) ex;
		}

		throw new UncategorizedScriptException("Failed to execute database script", ex);
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:29,代码来源:DatabasePopulatorUtils.java

示例6: getNextKey

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	ResultSet rs = null;
	try {
		stmt = con.createStatement();
		DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
		rs = stmt.executeQuery(getSequenceQuery());
		if (rs.next()) {
			return rs.getLong(1);
		}
		else {
			throw new DataAccessResourceFailureException("Sequence query did not return a result");
		}
	}
	catch (SQLException ex) {
		throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
	}
	finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:29,代码来源:AbstractSequenceMaxValueIncrementer.java

示例7: getNativeConnection

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
/**
 * Check for a ConnectionProxy chain, then delegate to doGetNativeConnection.
 * <p>ConnectionProxy is used by Spring's TransactionAwareDataSourceProxy
 * and LazyConnectionDataSourceProxy. The target connection behind it is
 * typically one from a local connection pool, to be unwrapped by the
 * doGetNativeConnection implementation of a concrete subclass.
 * @see #doGetNativeConnection
 * @see org.springframework.jdbc.datasource.ConnectionProxy
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getTargetConnection
 * @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
 * @see org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy
 */
@Override
public Connection getNativeConnection(Connection con) throws SQLException {
	if (con == null) {
		return null;
	}
	Connection targetCon = DataSourceUtils.getTargetConnection(con);
	Connection nativeCon = doGetNativeConnection(targetCon);
	if (nativeCon == targetCon) {
		// We haven't received a different Connection, so we'll assume that there's
		// some additional proxying going on. Let's check whether we get something
		// different back from the DatabaseMetaData.getConnection() call.
		DatabaseMetaData metaData = targetCon.getMetaData();
		// The following check is only really there for mock Connections
		// which might not carry a DatabaseMetaData instance.
		if (metaData != null) {
			Connection metaCon = metaData.getConnection();
			if (metaCon != null && metaCon != targetCon) {
				// We've received a different Connection there:
				// Let's retry the native extraction process with it.
				nativeCon = doGetNativeConnection(metaCon);
			}
		}
	}
	return nativeCon;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:38,代码来源:NativeJdbcExtractorAdapter.java

示例8: findDefaultColumnType

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
public List<String> findDefaultColumnType(String dbInfoId) throws Exception {
	DataSource ds = this.getDataSourceByDbInfoId(dbInfoId);
	Connection conn = null;
	ResultSet resultSet = null;
	try {
		conn = DataSourceUtils.getConnection(ds);
		DatabaseMetaData metaData = conn.getMetaData();
		resultSet = metaData.getTypeInfo();
		List<String> list = new ArrayList<String>();
		while (resultSet.next()) {
			String typeName = resultSet.getString("TYPE_NAME").toUpperCase();
			list.add(typeName);
		}
		return list;
	} finally {
		JdbcUtils.closeResultSet(resultSet);
		JdbcUtils.closeConnection(conn);
	}
}
 
开发者ID:bsteker,项目名称:bdf2,代码行数:20,代码来源:DbCommonServiceImpl.java

示例9: loadTablePrimaryKeys

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
private List<String> loadTablePrimaryKeys(String tableName)throws Exception{
	DataSource ds=this.getJdbcTemplate().getDataSource();
	Connection con = DataSourceUtils.getConnection(ds);
	List<String> primaryKeyList=new ArrayList<String>();
	Statement stmt = null;
	ResultSet rs=null;
	try{
		DatabaseMetaData metaData = con.getMetaData();
		rs = metaData.getPrimaryKeys(null, null, tableName.toUpperCase());
		while (rs.next()) {
			primaryKeyList.add(rs.getString("COLUMN_NAME"));
		}
	}finally{
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		JdbcUtils.closeConnection(con);
	}
	return primaryKeyList;
}
 
开发者ID:bsteker,项目名称:bdf2,代码行数:20,代码来源:EntityPR.java

示例10: queryForInt

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
public static int queryForInt(DataSource dataSource, String sql, Object... params) throws SQLException {
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        ps = DataSourceUtils.doGetConnection(dataSource).prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            ps.setObject(i + 1, params[i]);
        }

        rs = ps.executeQuery();
        if (rs.next()) {
            return rs.getInt(1);
        } else {
            return -1;
        }
    } finally {
        if (ps != null) {
            ps.close();
        }
        if (rs != null) {
            rs.close();
        }
    }
}
 
开发者ID:lodsve,项目名称:lodsve-framework,代码行数:25,代码来源:MyBatisUtils.java

示例11: existTable

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
@Override
public boolean existTable(String tableName, DataSource dataSource) throws Exception {
    Assert.notNull(dataSource);
    Assert.hasText(tableName);

    String name = dataSource.getConnection().getCatalog();
    PreparedStatement ps = null;
    ResultSet resultSet = null;

    try {
        ps = DataSourceUtils.doGetConnection(dataSource).prepareStatement(existTableSql(name, tableName));
        resultSet = ps.executeQuery();

        return resultSet.next() && resultSet.getInt("count") > 0;
    } finally {
        if (ps != null) {
            ps.close();
        }
        if (resultSet != null) {
            resultSet.close();
        }
    }
}
 
开发者ID:lodsve,项目名称:lodsve-framework,代码行数:24,代码来源:AbstractDialect.java

示例12: getConnection

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
@Override
public Connection getConnection() throws SQLException {
    TransactionProxy proxy = getProxy();
    if (proxy != null) {
        return proxy.getConnection();
    }
    //根据当前激活的数据源 获取jdbc链接
    DataSource dataSource = DataSourceHolder.currentDataSource().getNative();
    String dsId = switcher().currentDataSourceId();
    Connection connection = DataSourceUtils.getConnection(dataSource);
    proxy = new TransactionProxy(dsId, connection, dataSource);
    addProxy(proxy);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "DataSource (" + (dsId == null ? "default" : dsId) + ") JDBC Connection ["
                        + connection
                        + "] will"
                        + (proxy.isConnectionTransactional ? " " : " not ")
                        + "be managed by Spring");
    }

    return connection;
}
 
开发者ID:hs-web,项目名称:hsweb-framework,代码行数:25,代码来源:DynamicSpringManagedTransaction.java

示例13: beginTransaction

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
@Override
 public Object beginTransaction(final EntityManager entityManager, 
 		final TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException {
 	
 	Session session = (Session) entityManager.getDelegate();
 	if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
 		getSession(entityManager).getTransaction().setTimeout(definition.getTimeout());
 	}
 	entityManager.getTransaction().begin();
 	logger.debug("Transaction started");
 	session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
	 logger.debug("The connection instance is " + connection.toString());
	 logger.debug("The isolation level of the connection is " + connection.getTransactionIsolation() 
			 + " and the isolation level set on the transaction is " + definition.getIsolationLevel() );
	 DataSourceUtils.prepareConnectionForTransaction(connection, definition);
}
 	});
 	return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName());
 }
 
开发者ID:billchen198318,项目名称:bamboobsc,代码行数:22,代码来源:HibernateExtendedJpaDialect.java

示例14: executeSql

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
protected void executeSql(String path) {
    logger.info("executeSql : " + path);

    Resource resource = new ClassPathResource(path, getClass());
    ResourceDatabasePopulator rdp = new ResourceDatabasePopulator();
    rdp.addScript(resource);
    rdp.setSqlScriptEncoding("UTF-8");
    rdp.setIgnoreFailedDrops(true);
    rdp.setContinueOnError(false);

    try (Connection conn = DataSourceUtils.getConnection(dataSource)) {
        rdp.populate(conn);
    }
    catch (Exception e) {
        throw new IllegalStateException("executeSql failed, path=" + path, e);
    }
}
 
开发者ID:af-not-found,项目名称:blog-java2,代码行数:18,代码来源:SpringTestBase.java

示例15: checkConnection

import org.springframework.jdbc.datasource.DataSourceUtils; //导入依赖的package包/类
/**
 */
private void checkConnection() {
    Connection conn = DataSourceUtils.getConnection(jdbc.getDataSource());

    assertNotNull(conn);

    try {
        assertFalse(conn.isClosed());
        assertEquals(!ses.isWithinTransaction(), conn.getAutoCommit());
    }
    catch (SQLException e) {
        throw new RuntimeException(e);
    }

    verifySameInstance(conn);
}
 
开发者ID:apache,项目名称:ignite,代码行数:18,代码来源:CacheSpringStoreSessionListenerSelfTest.java


注:本文中的org.springframework.jdbc.datasource.DataSourceUtils类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。