我想使用 DataSource 接口连接到 Oracle 数据库,而不是在 java 中使用 DriverManager。我对此没有任何想法。请给我提供一个示例程序来做到这一点。
4
当你想使用一个数据源在这里是要走的路:
// Setup the datasource
DataSource ds = new OracleDataSource();// There is other DataSource offered by Oracle , check the javadoc for more information
ds.setDriverType("thin");
ds.setServerName("myServer");
ds.setPortNumber(1521);
ds.setDatabaseName("myDB");
ds.setUser("SCOTT");
ds.setPassword("TIGER");
// Get a JDBC connection
Connection c = ds.getConnection();
这是在掩护下做的。
然而,在现实生活中的项目中,你不会经常这样做。假设你构建了一个 web 应用程序。通常,你会以文本格式配置一个数据源,并将此配置放在你的容器上。稍后,您可以通过 JNDI 检索数据源 (请参阅 @ Radhamani Muthusamyanswer)。
2
首先创建一个Datasource
文件。数据源文件名可以在properties file
中给出。使用以下代码
ResourceBundle rb = ResourceBundle
.getBundle("com.cactus.xorail.properties.ConnectionProperties");
InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup("java:/"
+ rb.getString("Datasource"));
if (ds == null) {
throw new SQLException(
"Please configure datasource with name DS");
}
result = ds.getConnection();
result = ds.getConnection();
0
/ / 设置 DataSource 对象
oracle.jdbc.pool.OracleDataSource ds
= new oracle.jdbc.pool.OracleDataSource();
ds.setDriverType("thin");
ds.setServerName("localhost");
ds.setPortNumber(1521);
ds.setDatabaseName("XE"); // Oracle SID
ds.setUser("Herong");
ds.setPassword("TopSecret");
/ / 获取连接对象
con = ds.getConnection();
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(57条)