AccessDataSource.java~8~
资源名称:某公司的java培训教材 [点击查看]
上传用户:dinglihq
上传日期:2013-02-04
资源大小:99958k
文件大小:2k
源码类别:
Java编程
开发平台:
Java
- package com.cwj.DatabaseAccessDemo;
- /*运行本文件请确认是否已经将“Weblogic 8.x Client”添加至“Required Libraries”列表中,
- 其次需要在Weblogic Server中创建一个JNDI名称为“SQLServer”的DataSource,数据库指向
- */
- import javax.naming.*;
- import java.util.Properties;
- import java.sql.*;
- import java.util.*;
- //import com.beasys.jndi.WLEInitialContextFactory;
- import weblogic.jndi.*;
- public class AccessDataSource {
- Hashtable ht;
- Context ctx = null;
- javax.sql.DataSource ds = null;
- java.sql.Connection conn=null;
- Statement stat = null;
- ResultSet result = null;
- public AccessDataSource(){
- initialize();
- }
- public void initialize() {
- ht = new Hashtable();
- ht.put(Context.INITIAL_CONTEXT_FACTORY,
- "weblogic.jndi.WLInitialContextFactory");
- ht.put(Context.PROVIDER_URL, "t3://127.0.0.1:7001");
- try {
- ctx = new InitialContext(ht);
- ds = (javax.sql.DataSource) ctx.lookup("SQLServer");
- conn= ds.getConnection();
- // You can now use the conn object to create
- // a Statement object to execute
- // SQL statements and process result sets:
- stat = conn.createStatement();
- result = stat.executeQuery("select * from customers");
- // Do not forget to close the statement and connection objects
- // when you are finished:
- while (result.next()) {
- System.out.println(result.getString(1)+" "+result.getString(2));
- }
- if(result!=null){
- result.close();
- }
- if(stat!=null){
- stat.close();
- }
- if(conn!=null){
- conn.close();
- }
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- finally {
- try {
- ctx.close();
- }
- catch (Exception e) {
- // a failure occurred
- }
- }
- }
- }