本文整理汇总了Java中javax.sql.DataSource.getConnection方法的典型用法代码示例。如果您正苦于以下问题:Java DataSource.getConnection方法的具体用法?Java DataSource.getConnection怎么用?Java DataSource.getConnection使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.sql.DataSource
的用法示例。
在下文中一共展示了DataSource.getConnection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createDatabase
import javax.sql.DataSource; //导入方法依赖的package包/类
private void createDatabase(DataSource ds) throws IOException, SQLException
{
logger.info("Creating DB");
m_holdConnection = ds.getConnection();
m_holdConnection.setAutoCommit(false);
StringBuilder sb = new StringBuilder();
try(InputStreamReader reader = new InputStreamReader(getClass().getClassLoader()
.getResourceAsStream("create.sql")))
{
int ch;
while ((ch = reader.read()) != -1)
sb.append((char) ch);
}
String[] tableCommands = sb.toString().split(";");
Statement s = m_holdConnection.createStatement();
for (String command : tableCommands)
s.execute(command);
m_holdConnection.commit();
}
示例2: getJNDIConnection
import javax.sql.DataSource; //导入方法依赖的package包/类
public Connection getJNDIConnection() throws NamingException, SQLException {
Connection conn = null;
if (jdbcDriverClassName.equals("JNDI")) {
String path = jdbcURL;
if (!path.startsWith("java:")) {
path = "java:comp/env/" + path;
}
DataSource ds = EngineServlet.getDataSource(path);
if (ds == null) {
throw new NamingException(path + " not found in context");
}
conn = ds.getConnection();
}
return conn;
}
示例3: checkNormalSlaves
import javax.sql.DataSource; //导入方法依赖的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);
}
}
}
示例4: findTablePrimaryKeys
import javax.sql.DataSource; //导入方法依赖的package包/类
public List<String> findTablePrimaryKeys(String dbInfoId, String tableName) throws Exception {
List<String> primaryKeys = new ArrayList<String>();
Connection con = null;
ResultSet rs = null;
DataSource ds = this.getDataSourceByDbInfoId(dbInfoId);
try {
con = ds.getConnection();
DatabaseMetaData metaData = con.getMetaData();
rs = metaData.getPrimaryKeys(null, null, tableName.toUpperCase());
while (rs.next()) {
primaryKeys.add(rs.getString("COLUMN_NAME").toUpperCase());
}
return primaryKeys;
} finally {
JdbcUtils.closeResultSet(rs);
JdbcUtils.closeConnection(con);
}
}
示例5: getConnection
import javax.sql.DataSource; //导入方法依赖的package包/类
/**
* {@inheritDoc}
*
* @param datasourceName 取得するコネクションのデータソース名
*
* @see jp.co.future.uroborosql.connection.ConnectionSupplier#getConnection(java.lang.String)
*/
@Override
public Connection getConnection(final String datasourceName) {
try {
DataSource ds = dsMap.computeIfAbsent(datasourceName, DataSourceConnectionSupplierImpl::getNewDataSource);
final Connection connection;
synchronized (ds) {
connection = ds.getConnection();
}
boolean autoCommit = getAutoCommit(datasourceName);
if (connection.getAutoCommit() != autoCommit) {
connection.setAutoCommit(autoCommit);
}
boolean readOnly = getReadOnly(datasourceName);
if (connection.isReadOnly() != readOnly) {
connection.setReadOnly(readOnly);
}
int transactionIsolation = getTransactionIsolation(datasourceName);
if (transactionIsolation > 0 && connection.getTransactionIsolation() != transactionIsolation) {
connection.setTransactionIsolation(transactionIsolation);
}
return connection;
} catch (SQLException ex) {
throw new UroborosqlRuntimeException("Connection[" + datasourceName + "] can not be acquired.", ex);
}
}
示例6: createSchema
import javax.sql.DataSource; //导入方法依赖的package包/类
/**
* Creates new database scheme.
*
* @param dataSource the datasource
* @param name schema name
*/
public static void createSchema(DataSource dataSource, String name) {
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.executeUpdate(String.format(DDL_CREATE_SCHEMA, name));
} catch (SQLException e) {
throw new RuntimeException("Can not connect to database", e);
}
}
示例7: testBasicType
import javax.sql.DataSource; //导入方法依赖的package包/类
@Test
public void testBasicType() throws SQLException {
DataSource ds = DataSourceBuilder.create()
.build(DataSourceConfigProperties.builder("basic").withPropertySource("test_build.properties").build());
assertNotNull(ds);
assertEquals(DefaultBasicDataSource.class, ds.getClass());
assertEquals("jdbc:h2:mem:testdb", ((DefaultBasicDataSource) ds).getUrl());
assertEquals("sa", ((DefaultBasicDataSource) ds).getUsername());
try (Connection c = ds.getConnection()) {
assertNotNull(c);
}
}
示例8: initDB
import javax.sql.DataSource; //导入方法依赖的package包/类
@BeforeClass
public static void initDB() throws SQLException, IOException {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:h2/spring-test-h2.xml");
DataSource ds = (DataSource) context.getBean("dataSource");
try (Connection conn = ds.getConnection()) {
String createTableSql = readFile("user.ddl.sql");
Statement stmt = conn.createStatement();
stmt.execute(createTableSql);
stmt.execute("truncate table h2user");
insertUsers(stmt);
conn.commit();
}
}
示例9: runScript
import javax.sql.DataSource; //导入方法依赖的package包/类
public static void runScript(DataSource ds, String resource) throws IOException, SQLException {
Connection connection = ds.getConnection();
try {
ScriptRunner runner = new ScriptRunner(connection);
runner.setAutoCommit(true);
runner.setStopOnError(false);
runner.setLogWriter(null);
runner.setErrorLogWriter(null);
runScript(runner, resource);
} finally {
connection.close();
}
}
示例10: testCL
import javax.sql.DataSource; //导入方法依赖的package包/类
@Test
public void testCL() throws SQLException {
DataSource ds = DataSourceBuilder.create(ClassUtils.getDefaultClassLoader())
.build(DataSourceConfigProperties.builder("basic").withPropertySource("test_build.properties").build());
assertNotNull(ds);
assertEquals(DefaultBasicDataSource.class, ds.getClass());
assertEquals("jdbc:h2:mem:testdb", ((DefaultBasicDataSource) ds).getUrl());
assertEquals("sa", ((DefaultBasicDataSource) ds).getUsername());
try (Connection c = ds.getConnection()) {
assertNotNull(c);
}
}
示例11: doGetConnection
import javax.sql.DataSource; //导入方法依赖的package包/类
/**
* Actually obtain a JDBC Connection from the given DataSource.
* Same as {@link #getConnection}, but throwing the original SQLException.
* <p>Is aware of a corresponding Connection bound to the current thread, for example
* when using {@link DataSourceTransactionManager}. Will bind a Connection to the thread
* if transaction synchronization is active (e.g. if in a JTA transaction).
* <p>Directly accessed by {@link TransactionAwareDataSourceProxy}.
* @param dataSource the DataSource to obtain Connections from
* @return a JDBC Connection from the given DataSource
* @throws SQLException if thrown by JDBC methods
* @see #doReleaseConnection
*/
public static Connection doGetConnection(DataSource dataSource) throws SQLException {
Assert.notNull(dataSource, "No DataSource specified");
ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
if (conHolder != null && (conHolder.hasConnection() || conHolder.isSynchronizedWithTransaction())) {
conHolder.requested();
if (!conHolder.hasConnection()) {
logger.debug("Fetching resumed JDBC Connection from DataSource");
conHolder.setConnection(dataSource.getConnection());
}
return conHolder.getConnection();
}
// Else we either got no holder or an empty thread-bound holder here.
logger.debug("Fetching JDBC Connection from DataSource");
Connection con = dataSource.getConnection();
if (TransactionSynchronizationManager.isSynchronizationActive()) {
logger.debug("Registering transaction synchronization for JDBC Connection");
// Use same Connection for further JDBC actions within the transaction.
// Thread-bound object will get removed by synchronization at transaction completion.
ConnectionHolder holderToUse = conHolder;
if (holderToUse == null) {
holderToUse = new ConnectionHolder(con);
}
else {
holderToUse.setConnection(con);
}
holderToUse.requested();
TransactionSynchronizationManager.registerSynchronization(
new ConnectionSynchronization(holderToUse, dataSource));
holderToUse.setSynchronizedWithTransaction(true);
if (holderToUse != conHolder) {
TransactionSynchronizationManager.bindResource(dataSource, holderToUse);
}
}
return con;
}
示例12: validateInstance
import javax.sql.DataSource; //导入方法依赖的package包/类
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 {
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);
}
}
示例13: cleanJiraDataBaseForImport
import javax.sql.DataSource; //导入方法依赖的package包/类
/**
* Clean data base with 'MDA' JIRA project.
*/
@AfterClass
public static void cleanJiraDataBaseForImport() throws SQLException {
final DataSource datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null);
final Connection connection = datasource.getConnection();
try {
ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/upload/jira-drop.sql"), StandardCharsets.UTF_8));
} finally {
connection.close();
}
}
示例14: test8CommitAfterTimeOut
import javax.sql.DataSource; //导入方法依赖的package包/类
@Test
public void test8CommitAfterTimeOut() throws Exception {
Context ctx = cache.getJNDIContext();
DataSource ds2 = (DataSource) ctx.lookup("java:/SimpleDataSource");
ds2.getConnection();
GemFireTransactionDataSource ds =
(GemFireTransactionDataSource) ctx.lookup("java:/XAPooledDataSource");
UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
utx.begin();
Connection conn = ds.getConnection();
String sql = "create table newTable2 (id integer)";
Statement sm = conn.createStatement();
sm.execute(sql);
utx.setTransactionTimeout(30);
sql = "insert into newTable2 values (1)";
sm.execute(sql);
sql = "select * from newTable2 where id = 1";
ResultSet rs = sm.executeQuery(sql);
if (!rs.next()) {
fail("Transaction not committed");
}
sql = "drop table newTable2";
sm.execute(sql);
sm.close();
conn.close();
utx.setTransactionTimeout(1);
Thread.sleep(3000);
try {
utx.commit();
fail("exception did not occur on commit although transaction timed out");
} catch (Exception expected) {
}
}
示例15: check
import javax.sql.DataSource; //导入方法依赖的package包/类
public void check(DataSource dataSource) throws SQLException {
try {
conn = dataSource.getConnection();
} catch (SQLException ex) {
logger.warn("error open connection", ex);
throw ex;
} finally {
closeConnection();
}
}