[英]Program to connect Oracle Database using DataSource interface
我想使用DataSource接口連接到Oracle數據庫,不使用java中的DriverManager。 我對此並不了解。 請給我一個示例程序。
首先創建一個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();
當您想要使用DataSource時,可以采用以下方法:
// 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 Muthusamy的回答 )。
//設置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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.