本文整理汇总了Java中org.apache.commons.dbcp.BasicDataSource.getConnection方法的典型用法代码示例。如果您正苦于以下问题:Java BasicDataSource.getConnection方法的具体用法?Java BasicDataSource.getConnection怎么用?Java BasicDataSource.getConnection使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.commons.dbcp.BasicDataSource
的用法示例。
在下文中一共展示了BasicDataSource.getConnection方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createDb
import org.apache.commons.dbcp.BasicDataSource; //导入方法依赖的package包/类
private static BasicDataSource createDb(String dbName, String basePath, String[] files) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUsername("username");
dataSource.setPassword("password");
dataSource.setUrl("jdbc:h2:mem:test" + dbName);
try (Connection connection = dataSource.getConnection()) {
for (String f : files) {
String scriptPath = Paths.get(basePath, f).toString();
try (Statement statement = connection.createStatement() ) {
statement.executeUpdate("RUNSCRIPT FROM '" + scriptPath + "'"); //NOSONAR
}
}
} catch (SQLException e) {
log.error("Error while creating the in-memory H2 Database.", e);
}
return dataSource;
}
示例2: test
import org.apache.commons.dbcp.BasicDataSource; //导入方法依赖的package包/类
@Test
public void test() throws Exception {
try (Server server = new Server(new ServerConfiguration(folder.newFolder().toPath()))) {
server.start();
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl("jdbc:herddb:server:localhost:7000?");
dataSource.setDriverClassName(Driver.class.getName());
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM SYSTABLES")) {
int count = 0;
while (rs.next()) {
System.out.println("table: " + rs.getString(1));
count++;
}
assertTrue(count > 0);
}
dataSource.close();
}
}
示例3: getConnection
import org.apache.commons.dbcp.BasicDataSource; //导入方法依赖的package包/类
/**
* Gets the connection.
*
* @param name
* the name
* @return the connection
* @throws SQLException
* the SQL exception
*/
public static Connection getConnection(String name) throws SQLException {
name = name.trim();
BasicDataSource external = dss.get(name);
if (external == null) {
external = getDataSource(name);
}
Connection c = (external == null ? null : external.getConnection());
if (c != null) {
try {
c.setAutoCommit(true);
} catch (Exception e) {
// possible not support
}
}
return c;
}
示例4: getTables
import org.apache.commons.dbcp.BasicDataSource; //导入方法依赖的package包/类
/**
* getTables
*
* @param datasourceKey
* datasource to use
* @return a list of tables
*/
public List<String> getTables(String datasourceKey) {
List<String> tables = new ArrayList<String>();
String catalog = null;
String schemaPattern = null;
String tableNamePattern = null;
String[] types = { "TABLE" };
BasicDataSource dataSource = getDatabaseSource(datasourceKey);
ResultSet result = null;
Connection con = null;
try {
con = dataSource.getConnection();
result = con.getMetaData().getTables(catalog, schemaPattern, tableNamePattern, types);
while (result.next()) {
tables.add(result.getString(3));
}
} catch (Exception se) {
log.error("Unable to retrieve tables from datasource: " + datasourceKey, se);
} finally {
try {
if (result != null) {
result.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
log.error("Unable to close connection after select Data.", e);
}
}
return tables;
}
示例5: getPrimaryKeyForTable
import org.apache.commons.dbcp.BasicDataSource; //导入方法依赖的package包/类
/**
* getPrimaryKeyForTable
*
* @param datasourceKey
* datasource to use
* @param tableName
* name of table to retrieve primary key
* @return name of primary key
*/
public String getPrimaryKeyForTable(String datasourceKey, String tableName) {
String primaryKey = "";
Connection con = null;
ResultSet result = null;
String catalog = null;
String schema = null;
try {
BasicDataSource dataSource = getDatabaseSource(datasourceKey);
con = dataSource.getConnection();
result = con.getMetaData().getPrimaryKeys(catalog, schema, tableName);
while (result.next()) {
primaryKey = result.getString(4);
}
} catch (SQLException se) {
log.error("Unable to retrieve primary key for table: " + tableName, se);
} finally {
try {
if (result != null) {
result.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
log.error("Unable to close connection after select Data.", e);
}
}
return primaryKey;
}
示例6: setupDefaultTestCluster
import org.apache.commons.dbcp.BasicDataSource; //导入方法依赖的package包/类
@BeforeClass
public static void setupDefaultTestCluster() throws Exception {
System.setProperty("derby.drda.startNetworkServer", "true");
server = new NetworkServerControl(InetAddress.getByName("localhost"),
20000,
"admin",
"admin");
java.io.PrintWriter consoleWriter = new java.io.PrintWriter(System.out, true);
server.start(consoleWriter);
BasicDataSource source = new BasicDataSource();
source.setUrl("jdbc:derby://localhost:20000/memory:testDB;create=true");
source.setDriverClassName("org.apache.derby.jdbc.ClientDriver");
final String insertValues1 = "INSERT INTO person VALUES (1, 'Smith', null, '{number:\"123 Main\"}','mtrx', "
+ "'xy', 333.333, 444.444, 555.00, TIME('15:09:02'), DATE('1994-02-23'), TIMESTAMP('1962-09-23 03:23:34.234'),"
+ " 666.66, 1, -1, false)";
final String insertValues2 = "INSERT INTO person (PersonId) VALUES (null)";
try (Connection c = source.getConnection()) {
c.createStatement().execute("CREATE TABLE person\n" +
"(\n" +
"PersonID int,\n" +
"LastName varchar(255),\n" +
"FirstName varchar(255),\n" +
"Address varchar(255),\n" +
"City varchar(255),\n" +
"Code char(2),\n" +
"dbl double,\n" +
"flt float,\n" +
"rel real,\n" +
"tm time,\n" +
"dt date,\n" +
"tms timestamp,\n" +
"num numeric(10,2), \n" +
"sm smallint,\n" +
"bi bigint,\n" +
"bool boolean\n" +
")");
c.createStatement().execute(insertValues1);
c.createStatement().execute(insertValues2);
c.createStatement().execute(insertValues1);
}
BaseTestQuery.setupDefaultTestCluster();
}
示例7: createDataSource
import org.apache.commons.dbcp.BasicDataSource; //导入方法依赖的package包/类
private BasicDataSource createDataSource(Map<String, String> properties, String urlPattern) {
BasicDataSource dsPool = new BasicDataSource();
dsPool.setDriverClassName(DSPropertyUtil.getPropertyStringValue("driver", properties, null, null, true));
dsPool.setUsername(DSPropertyUtil.getPropertyStringValue("username", properties, null, null, true));
dsPool.setPassword(DSPropertyUtil.getPropertyStringValue("password", properties, null, null, true));
String url = DSPropertyUtil.getPropertyStringValue("url", properties, null, null, true);
if (null != urlPattern) {
url = DSPropertyUtil.replace(url, "{}", urlPattern);
}
dsPool.setUrl(url);
dsPool.setPoolPreparedStatements(DSPropertyUtil.getPropertyBooleanValue("poolingStatements", properties, null, true, true)); // 开启池的prepared
// 池功能
dsPool.setRemoveAbandoned(DSPropertyUtil.getPropertyBooleanValue("removeAbandoned", properties, null, true, true));
dsPool.setRemoveAbandonedTimeout(DSPropertyUtil.getPropertyIntegerValue("removeAbandonedTimeout", properties, null, 1000, true));
dsPool.setLogAbandoned(DSPropertyUtil.getPropertyBooleanValue("logAbandoned", properties, null, true, true));
dsPool.setInitialSize(DSPropertyUtil.getPropertyIntegerValue("initialSize", properties, null, 2, true));
dsPool.setMaxActive(DSPropertyUtil.getPropertyIntegerValue("maxActive", properties, null, 8, true));
dsPool.setMaxIdle(DSPropertyUtil.getPropertyIntegerValue("maxIdle", properties, null, 8, true));
dsPool.setMinIdle(DSPropertyUtil.getPropertyIntegerValue("minIdle", properties, null, 0, true));
dsPool.setMaxWait(DSPropertyUtil.getPropertyIntegerValue("maxWait", properties, null, 10000, true));
dsPool.setTimeBetweenEvictionRunsMillis(DSPropertyUtil.getPropertyIntegerValue("timeBetweenEvictionRunsMillis", properties, null, -1, true));
dsPool.setTestOnBorrow(DSPropertyUtil.getPropertyBooleanValue("testOnBorrow", properties, null, false, true));
dsPool.setTestOnReturn(DSPropertyUtil.getPropertyBooleanValue("testOnReturn", properties, null, false, true));
dsPool.setTestWhileIdle(DSPropertyUtil.getPropertyBooleanValue("testWhileIdle", properties, null, false, true));
String validationQuery = DSPropertyUtil.getPropertyStringValue("validationQuery", properties, null, null, false);
if (null != validationQuery) {
dsPool.setValidationQuery(validationQuery);
}
int timeout = DSPropertyUtil.getPropertyIntegerValue("", properties, null, -1, false);
if (timeout > -1) {
dsPool.setValidationQueryTimeout(timeout);
}
dsPool.setNumTestsPerEvictionRun(DSPropertyUtil.getPropertyIntegerValue("numTestsPerEvictionRun", properties, null, 10, true));
dsPool.setMinEvictableIdleTimeMillis(DSPropertyUtil.getPropertyIntegerValue("minEvictableIdleTimeMillis", properties, null, 60000, true));
// mysql:select 1
// oracle:select 1 from dual
// sqlserver:select 1
// jtds:select 1
boolean openTest = DSPropertyUtil.getPropertyBooleanValue("openTest", properties, null, false, false);
if (openTest) {
try {
Connection conn = dsPool.getConnection();
conn.close();
log.info("test open database success.");
} catch (Exception e) {
throw new DataSourceException("test open database error: " + e.getMessage(), e);
}
}
return dsPool;
}
示例8: selectData
import org.apache.commons.dbcp.BasicDataSource; //导入方法依赖的package包/类
/**
* selectData
*
* @param dataSourceKey
* the key to locate the datasource to use
* @param selectStmnt
* string representation of the sql statement to execute
* @return Result set of the statement execution
*/
public List<Map<String, Object>> selectData(String dataSourceKey, String selectStmnt) {
Connection conn = null;
Statement stmt = null;
ResultSet resultSet = null;
List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
Map<String, Object> row = null;
try {
BasicDataSource dataSource = getDatabaseSource(dataSourceKey);
conn = dataSource.getConnection();
stmt = conn.createStatement();
resultSet = stmt.executeQuery(selectStmnt.toString());
ResultSetMetaData metaData = resultSet.getMetaData();
Integer columnCount = metaData.getColumnCount();
while (resultSet.next()) {
row = new HashMap<String, Object>();
for (int i = 1; i <= columnCount; i++) {
row.put(metaData.getColumnName(i), resultSet.getObject(i));
}
resultList.add(row);
}
} catch (SQLException sqlex) {
log.error("Unable to execute query.", sqlex);
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
log.error("Unable to close connection after select Data.", e);
}
}
return resultList;
}
示例9: createDataSource
import org.apache.commons.dbcp.BasicDataSource; //导入方法依赖的package包/类
private BasicDataSource createDataSource(Map<String, String> properties, Map<String, String> decryptProperties, String urlPattern) {
BasicDataSource dsPool = new BasicDataSource();
dsPool.setDriverClassName(getPropertyStringValue("driver", properties, null, null, true));
dsPool.setUsername(getPropertyStringValue("username", properties, null, null, true));
dsPool.setPassword(getPropertyStringValue("password", properties, null, null, true));
String url = getPropertyStringValue("url", properties, null, null, true);
if (null != urlPattern) {
url = StringUtils.replace(url, "{}", urlPattern);
}
dsPool.setUrl(url);
dsPool.setPoolPreparedStatements(getPropertyBooleanValue("poolingStatements", properties, null, true, true)); // 开启池的prepared statement 池功能
dsPool.setRemoveAbandoned(getPropertyBooleanValue("removeAbandoned", properties, null, true, true));
dsPool.setRemoveAbandonedTimeout(getPropertyIntegerValue("removeAbandonedTimeout", properties, null, 1000, true));
dsPool.setLogAbandoned(getPropertyBooleanValue("logAbandoned", properties, null, true, true));
dsPool.setInitialSize(getPropertyIntegerValue("initialSize", properties, null, 2, true));
dsPool.setMaxActive(getPropertyIntegerValue("maxActive", properties, null, 8, true));
dsPool.setMaxIdle(getPropertyIntegerValue("maxIdle", properties, null, 8, true));
dsPool.setMinIdle(getPropertyIntegerValue("minIdle", properties, null, 0, true));
dsPool.setMaxWait(getPropertyIntegerValue("maxWait", properties, null, 10000, true));
dsPool.setTimeBetweenEvictionRunsMillis(getPropertyIntegerValue("timeBetweenEvictionRunsMillis", properties, null, -1, true));
dsPool.setTestOnBorrow(getPropertyBooleanValue("testOnBorrow", properties, null, false, true));
dsPool.setTestOnReturn(getPropertyBooleanValue("testOnReturn", properties, null, false, true));
dsPool.setTestWhileIdle(getPropertyBooleanValue("testWhileIdle", properties, null, false, true));
String validationQuery = getPropertyStringValue("validationQuery", properties, null, null, false);
if (null != validationQuery) {
dsPool.setValidationQuery(validationQuery);
}
// dsPool.setValidationQueryTimeout(timeout);
dsPool.setNumTestsPerEvictionRun(getPropertyIntegerValue("numTestsPerEvictionRun", properties, null, 10, true));
dsPool.setMinEvictableIdleTimeMillis(getPropertyIntegerValue("minEvictableIdleTimeMillis", properties, null, 60000, true));
// mysql:select 1
// oracle:select 1 from dual
// sqlserver:select 1
// jtds:select 1
boolean openTest = getPropertyBooleanValue("openTest", properties, null, false, false);
if (openTest) {
try {
Connection conn = dsPool.getConnection();
conn.close();
log.info("test open database success.");
} catch (Exception e) {
throw new DataSourceException("test open database error: " + e.getMessage(), e);
}
}
return dsPool;
}