Help me understand JDBC connections using DataSource objects

I'm writing a simple Java server application that accepts connections from multiple clients via RMI, connects to a SQL Server 2000 database via Microsoft's SQL 2000 JDBC driver, gets some data, and returns it to the client. The server application will handle every SQL database connection. However, it must be able to establish multiple simultaneous connections, since multiple clients may connect at the same time and request data.
Sounds like a simple multi-threaded server that utilizes a connection pool for database connectivity, right? Well, if I want to do that, I have to register a PooledDataSource object with JNDI. My server threads that are handling requests will simply grab connections out of the pool to retrieve data (presumably).
This seems like a fairly simple server application; however, all the information and tutorials I've read on using DataSource objects for database connections rather than DriverManager.getConnection() mention XML config files, J2EE application servers, Tomcat, WebSphere, etc. I really don't want to have to deal with all that just to get connection pooling and not have to use the DriverManager.getConnection() method.
Is there a simple way to use DataSource objects without installing a lot of extra junk on my server?

Thanks, diazlara. Your response was exactly what I needed to know. All the information I've read prior to this suggested that I had to have a J2EE server running, and that I had to register the DataSource object with JNDI. If you ladies and gents could take a quick look at this and let me know if I'm doing it correctly, I'd appreciate it.
As proflux suggested, I wrote a connection manager:
import java.sql.*;
import javax.sql.*;
import com.microsoft.jdbcx.sqlserver.*;
public class SQLConnectionManager {
   private static ConnectionPoolDataSource connectionPool;
   // Initialize the connection manager
   public SQLConnectionManager() {
      init();
   // Retrieve a connection from the connection pool and return it
   public static Connection getConnection() {
      Connection connection = null;
      try {
         connection = connectionPool.getPooledConnection("myUsername", "myPassword").getConnection();
      catch (SQLException ex) {
         System.err.println("A problem occurred while getting a connection from the pool.");
         ex.printStackTrace();
      return connection;
   // Initialize the datasource and connection pool
   private static void init() {
      SQLServerDataSource mds = new SQLServerDataSource();
      mds.setDescription("MS SQLServerDataSource");
      mds.setServerName("127.0.0.1");
      mds.setPortNumber(1433);
      mds.setDatabaseName("SomeTable");
      mds.setSelectMethod("cursor");
      connectionPool = (ConnectionPoolDataSource) mds;
}As you can see, I'm hard-coding the username and password for testing purposes. I'll incorporate a login/authentication system for any production code that I use this in.
Once the SQLConnectionManager is created, connections can be retrieved as follows:
      Connection connection = null;
      try {
         connection = SQLConnectionManager.getConnection();
         System.out.println("** Got a SQL database connection from the pool");
         DatabaseMetaData metaData = connection.getMetaData();
         ResultSet rs = metaData.getCatalogs();
         while (rs.next()) {
            System.out.println("\tcatalog: " + rs.getString(1));
         rs.close();
         connection.close();
      catch (SQLException ex) {
         System.out.println("An exception occurred while connecting to the SQL Database:");
         ex.printStackTrace();
      }So, how does that look? I tested it out, and it seems to work just fine. Using this code, I am getting a connection from a pool, correct? I want to make sure of that. Also, are there any inherent weaknesses or flaws with this method that I need to be aware of?
Thanks so much for all the helpful responses.

Similar Messages

  • Retrieve db connection using datasource object

    The problem is: i can't retrieve the connection to database
    using datasource object in jsp.
    my jsp was build by Oracle9i Report Builder,then deployed
    to OC4J jsp container,
    i define the datasource at container level,
    but an error "log on not specified" arise.
    is it possible to use datasource object in such a way or not?
    thanks you for your help.

    What is the full Java and os versions you are using to compile and to run. Note that with JDEV the platform used for your code may be different than the platform used by JDEV itself.
    Please modify all of your exception handlers to print the stack trace. Add this as the first line in each handler.
    ex.printStackTrace();The stacktrace contains important information about where the problem really occured.
    See the Java docs for NamingException - http://docs.oracle.com/javase/6/docs/api/javax/naming/NamingException.html
    >
    This is the superclass of all exceptions thrown by operations in the Context and DirContext interfaces. The nature of the failure is described by the name of the subclass. This exception captures the information pinpointing where the operation failed, such as where resolution last proceeded to.
    •Resolved Name. Portion of name that has been resolved.
    •Resolved Object. Object to which resolution of name proceeded.
    •Remaining Name. Portion of name that has not been resolved.
    •Explanation. Detail explaining why name resolution failed.
    •Root Exception. The exception that caused this naming exception to be thrown.

  • Understanding JDBC connections

    Understanding JDBC connections
    Hello,
    I have problems with my JDBC connections, for example I restart de application server and then I view the log I found the next:
    (I)
    07/01/12 20:39:08 DataSource logwriter activated...
    jdbc:oracle:thin:@sipol01:1521:orcl: Started
    jdbc:oracle:thin:@sipol01:1521:orcl: Started
    com.evermind.sql.OrionPooledDataSource@1b446d1: Started
    07/01/12 20:39:08 DataSource logwriter activated...
    jdbc:oracle:thin:@sipol01:1521:orcl: Started
    jdbc:oracle:thin:@sipol01:1521:orcl: Started
    com.evermind.sql.OrionPooledDataSource@ae533a: Started
    07/01/12 20:39:09 DataSource logwriter activated...
    jdbc:oracle:thin:@sipol01:1521:orcl: Started
    jdbc:oracle:thin:@sipol01:1521:orcl: Started
    com.evermind.sql.OrionPooledDataSource@9444d1: Started
    07/01/12 20:39:09 DataSource logwriter activated...
    jdbc:oracle:thin:@sipol01:1521:orcl: Started
    jdbc:oracle:thin:@sipol01:1521:orcl: Started
    com.evermind.sql.OrionPooledDataSource@61a907: Started
    and then
    (II)
    Created new physical connection: com.evermind.sql.DriverManagerXAConnection@8420ae
    null: Connection com.evermind.sql.DriverManagerXAConnection@8420ae allocated (Pool size: 0)
    null: Releasing connection com.evermind.sql.DriverManagerXAConnection@8420ae to pool (Pool size: 1)
    (III)
    null: Releasing connection com.evermind.sql.DriverManagerXAConnection@324ff to pool (Pool size: 1)
    null: Releasing connection com.evermind.sql.DriverManagerXAConnection@324ff to pool (Pool size: 1)
    null: Releasing connection com.evermind.sql.DriverManagerXAConnection@324ff to pool (Pool size: 1)
    And then..
    (IV)
    null: Releasing connection com.evermind.sql.DriverManagerXAConnection@5d5033 to pool (Pool size: 1)
    com.evermind.sql.OrionCMTDataSource@fea539: Cache timeout, closing connection (Pool size: 0)
    com.evermind.sql.OrionCMTDataSource@1145cc: Cache timeout, closing connection (Pool size: 0)
    I have some questions about it:
    1. Why OC4J open Pool connections and where you configure this value?
    2. What is the mean of “serial” after OrionPooledDataSource@?
    3. What is the mean of “serial” after DriverManagerXAConnection@?
    4. What is the mean of “Releasing connection…” and why Release “324ff “ many times?? (Part III).
    If the serial is the id of the connection..
    5. When Cache timeout appears, I try to find in the log when the connection closing was open, but I didn’t find anything. What that means??
    Thanks your help.
    Jeanette

    Okay, thanks John. Sorry for using the wrong forum.

  • Problem JDBC Connection using OCI Driver on Weblogic Portal on Linux

    Hi Team,
    I want a JDBC connection using OCI Driver in Weblogic Portal 8.1 sp4 on Linux. When I had tested using JDBC connection using Plain Java Code it is working. Also when I create the OCI Connection Weblogic Connection Pool it is working.
    But My Requirement is to create the connection using Java Code in Portal Application
    But When I create OCI connection in the code it is throwing NO SUITABLE DRIVER Found.
    ---------- Code in Plain Java Code ------------ Same code is used in Weblogic Portal Application --------------------------------
         public static void main(String[] args) throws Exception{
              Class.forName("oracle.jdbc.driver.OracleDriver");
              DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
              String url="jdbc:oracle:oci8:@TESTDB";
              Properties props = new Properties();
         props.put("user","scott");
         props.put("password","tiger");
              conn=DriverManager.getConnection(url,props);
    When I am using the same code in Weblogic Portal and Deployed on Weblogic Portal Server 8.1 SP4 it is throwing following error.
    -------------- Exception on Server Log --------------------
    java.sql.SQLException: No suitable driver
    at java.sql.DriverManager.getConnection(Ljava.lang.String;Ljava.util.Properties;Ljava.lang.ClassLoader;)Ljava.sql.Connection;(Unknown Source)
    at java.sql.DriverManager.getConnection(Ljava.lang.String;Ljava.util.Properties;)Ljava.sql.Connection;(Unknown Source)
    My Environment is
    LINUX
    Weblogic 8.1 SP4
    Oracle 9i Client on Same Machine
    Oracle 10g Server on Different Machine
    My Environment Variables on the Linux Server also set properly as following
    PATH=/apps/pmaaum/ant/apache-ant-1.6.5/bin:.:/apps/beahomedev/jdk142_05/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/apps/oracle/ora9i/product/9.2.0/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/apps/oracle/ora9i/bin
    LD_LIBRARY_PATH=/usr/lib:/apps/oracle/ora9i/product/9.2.0/lib:/apps/oracle/ora9i/product/9.2.0/lib32:/apps/oracle/ora9i/product/9.2.0/rdbms/lib:/usr/openwin/lib:/apps/oracle/ora9i/product/9.2.0/jdbc/lib
    JAVA_HOME=/apps/beahomedev/jdk142_05
    JDBC_LIB=/apps/oracle/ora9i/product/9.2.0/jdbc/lib
    CLASSPATH=:.:/apps/beahomedev/jdk142_05/lib/rt.jar:/apps/oracle/ora9i/product/9.2.0/jdbc/lib/classes12.jar
    Please help me, Let me know if you required anything.
    Thanks in Advance
    Vishnu
    Edited by: vishnuk on Oct 23, 2009 4:07 AM
    Edited by: vishnuk on Oct 23, 2009 4:10 AM

    Hi Vishnu
    Looks like a classloader issue. BEA class loader is very tricky. Any jar added manually in classpath, will end up loading only those classes. Any imports that we have in any of those classes do not get loaded. Anyhow, coming to your point, add classes12.jar inside your portal web project Web-Inf/lib folder and see if that helps. Usually thats where we put all the JARs for 8.1 SPxx applications. If this still breaks, then remove the jar from web-inf/lib folder and add under your portal app App-Inf/lib folder. First try with app-inf/lib folder having this jar. If not then with web-inf/lib. Basically web-inf is specific to that web app only. If you have a different app having this jdbc code, then put under app-inf/lib folder. Make sure that you remove the classes12.jar that you added in classpath either in env variable or in setdomainenv.cmd file.
    When weblogic uses native OCI Drivers, it refers to jars at this location: ....\beawlp814\weblogic81\server\ext\jdbc\oracle\10g or 9g. Try using one of these jars and see if that works. Most of the times I used these jars only for oracle specific native drivers.
    Word of caution. Try to use Connection Pool and a DataSource created in weblogic console for your jdbc code. This Datasource can still use the Oracle drivers that you want (instead of BEA Weblogic wrapper oci drivers) located in above location. Use JNDI Lookup and get Datasource and then connection. This is more recommended approach with many advantages then using DriverManager approach..
    Goud

  • Help needed understanding this connection

    I am trying to follow some previous written code to understand JDBC better. When i have previously connected to a database, i have created a connection and then called it up when needed. In this code i have found though, they seem to use somthing called a datasource?
    public static Connection getXADBConnection() { Connection conn = null; DataSource ds = null; try { Object obj = lookup(MovieConstants.MOVIE_XA_DATASOURCE_NAME); ds = (DataSource) narrow(obj, DataSource.class); conn = ds.getConnection(); } catch (SQLException ex) { throw new DAORuntimeException(ex); } return conn; }
    So is datasource a connection already provided?? If so, is it better to use a datasource or to register through a driver manager? Also, if its not too much to ask, i am struggling to understand the first two lines in the try loop, what exactly is this doing?
    cheers

    nick2price wrote:
    ...try loop...Unless that was a typo, I think you should put off learning JDBC for a while and start with the basics.
    Start here:
    [http://java.sun.com/docs/books/tutorial/]

  • Jdbc connectivity using type 4 driver using oracle10g

    Hi while running a jdbc program using type 4 driver using oracle 10 g I am Getting following exception
    java.lang.NullPointerException
    java.lang.NullPointerException
    at Type4ConnectTest.main(Type4ConnectTest.java:31)
    Exception in thread "main" java.lang.ClassNotFoundException: oracle.jdbc.driver.
    OracleDriver
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:169)
    at Type4ConnectTest.main(Type4ConnectTest.java:15)
    My Program Code is..
    import java.sql.*;
    class Type4ConnectTest
    public static void main(String args[])throws Exception
    Connection con=null;
    Statement st=null;
    ResultSet rs=null;
    try
    // DriverManager.registerDriver(new Oracle:jdbc:OracleDriver());
    Class.forName("oracle.jdbc.OracleDriver");
    String url="jdbcracle:thin:@localhost:1521";
    con=DriverManager.getConnection(url,"sarika","sarika");
    catch(NullPointerException e)
    System.out.println("e");
    e.printStackTrace();
    finally
    try
    con.close();
    st.close();
    rs.close();
    catch(Exception e)
    System.out.println(e);
    e.printStackTrace();
    I also set path of ojdbc14.jar and orai18n.jar in environment variable.
    pls help to solve the problem

    Class.forName("SOME_DRIVER_CLASS");Is tricky to use because it will compile not needing to reference the vendors jar file.
    You have to remember to deploy it though where ever you plan to run this program.
    If you are running from command line
    java -cp PATH_TO_JAR Type4ConnectTest

  • Jdbc connection using oracle thin driver( using jdk1.4 and oracle8 )

    hello ..
    while i was tring to connection using oracle thin driver and jdk1.4 am getting the below error message. i have set the class path for the driver also. am using oracle8 personal edition and jdk1.4.
    [java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
            at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
            at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
            at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:333)
            at oracle.jdbc.driver.OracleConnection.<init>(OracleConnection.java:404)
            at oracle.jdbc.driver.OracleDriver.getConnectionInstance(OracleDriver.ja
    va:468)
            at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:314)
            at java.sql.DriverManager.getConnection(DriverManager.java:512)
            at java.sql.DriverManager.getConnection(DriverManager.java:171)
            at Connexa.main(Connexa.java:18)[/b]
    Press any key to continue...
    my program is....
    import java.sql.*;                                          
    import java.io.*;
    import java.util.*;
    import oracle.jdbc.driver.*;
    // needed for new BFILE class
    import oracle.sql.*;
       public class Connexa {
      public static void main (String args []) throws Exception {
            Statement stmt=null; 
      try{
        // Load the Oracle JDBC driver                            
        //DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    Class.forName("oracle.jdbc.driver.OracleDriver");
        // Connect to the database
        // You can put a database name after the @ sign in the connection URL.
    Connection conn =
    DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","tiger");
        //Connection conn =
        //  DriverManager.getConnection ("jdbc:odbc:datasource", "system", "manager");
        stmt = conn.createStatement ();
    catch (SQLException e)
          e.printStackTrace();

    The code itself is fine; the problem is with one of:
    1) the connection URL
    2) intermediate networking
    3) the database itself
    1) your connection URL is "jdbc:oracle:thin:@127.0.0.1:1521:orcl"
    - is Oracle really running on the default port, 1521
    - is the installation SID really "orcl"
    2) lots of possibilities, but only a couple are likely
    - is TCP/IP configured and running on your host
    - is there a persoanl firewall rpduct running? perhaps it's blocking the connection
    3) Is Oracle running?
    Is the listener running?

  • Using DataSource object

    Hi,
    how can I connect to a database using a javax.sql.DataSource??
    how can I obtain a javax.sql.DataSource object??
    Do I need to implement the javax.sql.DataSource to get a connection through it??
    thanks,
    Roger Silva

    DataSource implementations are numerous, but one that I can recommend (and use) is Tyrex. Tyrex comes with Tomcat4.x. See www.tyrex.org.
    Typically a DataSource instance is obtained by calling JNDI which calls a factory that creates a DataSource implementation and configures it from some configuration source. In the case of Tomcat db details are obtained from a resource reference in its configuration xml file.
    If you know the package (or can get hold of source that shows how to initialise it) then you can create the DataSource instance yourself.
    For example using Tyrex you can do the following to get a Connection Pooling instance:
    EnabledDataSource ds = new EnabledDataSource();
    ds.setDescription(..);
    ds.setLoginTimeout(..);
    ds.setUser(..);
    ds.setPassword(..);
    ds.setDriverName(..);
    ds.setDriverClassName(..);
    ServerDataSource sds = new ServerDataSource((javax.sql.XADataSource) ds);Dave

  • Help..problems with connection using Skype

    Hi, I have BT broadband option1 which I must say is very stable and generally fast enough for what I require. However when I use Skype the video is very blocky and freezes sometimes, audio is fine. Skype reports that my connection is bad and suggests I turn off video but my son and Grandson live in Australia so Skype is an essential application for me and the wife. I have tried another computer which behaves exactly the same so I am guessing it is my Broadband or Home Network. I changed the BT Home hub 2 for a new Netgear N150 to see if that improved it but alas no. I have port forwarded the Skype port to the computer but that has not helped either.
    The connection speeds reported by BT speed test and Netgear are 448 upstream and 7616 downstream..
    Is there anything wrong with my broadband connection or does anybody know how I can improve the skype video 

    Hi Paul
    Speaking from my experience as Jolly mentioned I was the other guy with the same problem. I could just not work out why I was getting a report from Skype all the time that my connection was not suitable for good video and to just use voice. My upload is the same as yours and is definitely sufficient for video.
    I have a BT Home Hub 1 and after getting pretty fed up I just decided to do a Factory Reset and luckily it worked. You may want to revert back your your BT Box and do a reset just to see if it works because that's what I did.
    As for port forwarding you should not have to do that as Skype and probably your router is UPnP ( Universal Plug and Play ) which does the port forwarding for you automatically.
    Try looking in the logs of your router to see if anything stands out as been wrong.
    In Skype you can get connection details from it. While you are doing a video call if you go to the top of the program and click on ‘Call’ and then ‘Call Technical Info’ and left click and copy what is in that screen and post it in here. From there we can tell what speed you are uploading.
    If it seems that you are uploading OK it may be the other ends download speed as that can also effect the connection between you and them.

  • Need help in DB2 JDBC connection from JDeveloper extension

    Hi,
    I am using JDeveloper extension to build my application. Here in the preferences, I have a UI in which I need to specify DB2 database connection parameters for establishing JDBC connection. After copying the required driver jar and license jar to the extension folder and specifying the CLASSPATH in extension.xml file, I am able to get the DB Connection. But the issue here is, I do not want the user to copy the driver jars to the extension path and neither to hardcode the driver CLASSPATH in extension.xml. Instead, if the user loads the driver jar in the CLASSPATH using command line, after launching JDev plug-in, I need to still be able to connect to the DB2 JDBC which is not happening. I am getting the error which says "Missing class com.ibm.db2.jcc.DB2Driver". I have ensured that the CLASSPTH is set for the driver and licensing jars for DB2. How can I get rid of this error without specifying the classpath in extension.xml file.
    Thanks,
    Sudha.
    Edited by: sudha.singh on Dec 13, 2010 1:08 AM
    Edited by: sudha.singh on Dec 13, 2010 1:08 AM

    drivers for DB2 for the JDBC adapter.
    1. db2jcc.jar
    2. db2_license_cu.jar
    3. db2_license_cisuz.jar
    Driver = com.ibm.db2.jcc.DB2Driver
    URL = jdbc:db2://<hostname>:5021/<dbname>:
    http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/ad/rjvjcdif.htm
    http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.apdv.java.doc/doc/t0010264.htm

  • JDBC Connection Using ColdFusion DataSource

    We are using ColdFusion MX 6 and oracle 10g.
    I am trying to code a JAVA JDBC database connection class by
    simplely pass ColdFusion datasouce name.
    i.e, instead of passing URL, user id and password, I hope my
    JAVA class can recognize ColdFusion datasource.
    Is this possible without a J2EE environment?
    If you have done this, please advice.

    DataSource is an interface which allows vendors and developers to implement their means of managing Connection objects (to add features like connection pooling, etc). You can find out about DataSource in API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/sql/DataSource.html
    DriverManager on the other hand is a class which registers Drivers and uses them to produce Connection objects:
    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/DriverManager.html

  • Trying To make DB connection using DataSource

    Hi ,
    I am working on Jdev 11g . Getting exception while trying to execute below code:
    import java.sql.*;
    import java.util.Hashtable;
    import javax.naming.*;
    import javax.sql.*;
    final class GetConnection {
    /** Uses JNDI and Datasource (preferred style). */
    static Connection getJNDIConnection(){
    // String DATASOURCE_CONTEXT = "java:comp/env/jdbc/blah";
    String DATASOURCE_CONTEXT = "JNDIDataSource-0";
    // String DATASOURCE_CONTEXT = "TESTJNDI_CONN";
    System.out.println("Control till here :1");
    Connection result = null;
    try {
    Context initialContext = new InitialContext();
    if ( initialContext == null){
    System.out.println("JNDI problem. Cannot get InitialContext.");
    System.out.println("Control till here :2");
    Hashtable<String, String> table = new Hashtable<String, String>();
    System.out.println("Here");
    table.put(Context.INITIAL_CONTEXT_FACTORY,
    "weblogic.jndi.WLInitialContextFactory");
    System.out.println("Control till here :3");
    table.put(Context.PROVIDER_URL, "hostName");
    System.out.println("Control till here :4");
    table.put(Context.SECURITY_PRINCIPAL, "weblogic");
    System.out.println("Control till here :5");
    table.put(Context.SECURITY_CREDENTIALS, "weblogic123");
    System.out.println("Control till here :6");
    initialContext = new InitialContext(table);
    System.out.println("Control till here :7");
    initialContext = new InitialContext(table);
    System.out.println("Control till here :8");
    DataSource datasource = (DataSource)initialContext.lookup(DATASOURCE_CONTEXT);
    DataSource source = (DataSource)new InitialContext().lookup("DataSource");
    // result = source.getConnection();
    System.out.println("Control till here :9");
    if (datasource != null) {
    System.out.println("Control till here :3");
    result = datasource.getConnection();
    System.out.println("Control till here :4");
    else {
    System.out.println("Failed to lookup datasource.");
    catch ( NamingException ex ) {
    System.out.println("Cannot get connection: 1" + ex);
    catch(SQLException ex){
    System.out.println("Cannot get connection: 2" + ex);
    return result;
    public static void main(String[] args) throws Exception {
    //WBSCallingProc WbsProc = new WBSCallingProc();
    String returnValue;
    GetConnection getConnection = new GetConnection();
    // returnValue =home.callingProcedure();
    Connection returnValue1 =getConnection.getJNDIConnection();
    System.out.println("returnValue1 " + returnValue1);
    Log
    Control till here :1
    Control till here :2
    Here
    Control till here :3
    Control till here :4
    Control till here :5
    Control till here :6
    Cannot get connection: 1javax.naming.NamingException: String index out of range: -1
    returnValue1 null
    Can anyone please help me here.Many Thanks.
    Regards
    Kumar

    What is the full Java and os versions you are using to compile and to run. Note that with JDEV the platform used for your code may be different than the platform used by JDEV itself.
    Please modify all of your exception handlers to print the stack trace. Add this as the first line in each handler.
    ex.printStackTrace();The stacktrace contains important information about where the problem really occured.
    See the Java docs for NamingException - http://docs.oracle.com/javase/6/docs/api/javax/naming/NamingException.html
    >
    This is the superclass of all exceptions thrown by operations in the Context and DirContext interfaces. The nature of the failure is described by the name of the subclass. This exception captures the information pinpointing where the operation failed, such as where resolution last proceeded to.
    •Resolved Name. Portion of name that has been resolved.
    •Resolved Object. Object to which resolution of name proceeded.
    •Remaining Name. Portion of name that has not been resolved.
    •Explanation. Detail explaining why name resolution failed.
    •Root Exception. The exception that caused this naming exception to be thrown.

  • JDBC connections using resource file

    I have heard that a resource file can be used to
    assign an URL and DB2 driver to establish a connection.
    What is a resource file and how can this be done?
    We have several URL and DB2 drivers to assign depending on what server we are processing on.
    thanks

    Hi,
    here's a sample:
    try {
    Properties properties = new Properties();
    properties.load(instance.getClass().getResourceAsStream("/sqlhandler.properties"));
    String driver = properties.getProperty("jdbc.driver");
    String url = properties.getProperty("jdbc.url");
    String login = properties.getProperty("jdbc.login");
    String password = properties.getProperty("jdbc.password");
    Class.forName(driver);
    connection = DriverManager.getConnection(url,login,password);
    The resource I use is a properties file that is (in this instance) located in the same place as class file. You can fully qualify the location of the resource if you wish.
    Hope this helps
    cheers
    Dave

  • Need help with Thin JDBC connecting Oracle to SQL server.

    I am fairly new to JAVA. We have ORACLE 8.1.7 running on Solaris 8. I have a need to
    periodically extract data from ORACLE DB and transfer it to SQL Server. I am limited to
    moving data from the ORACLE/UNIX environment to SQL Server side.
    From what I have read, Server-side Thin driver should work.
    1) Are there any issues in trying to achieve this with ORACLE running on the UNIX platform?
    2) Will the Server-side Thin driver talk to both the DBs ?
    3) Is it possible to provide some sample code ?
    Thanks in advance,
    Solomon

    Quattro,
    I had complete success in reading from Oracle and writing to SQL Server. First of all let me thank you for all your help. I do have one last request. Its more on optimization than any thing else.
    I was trying to optimize my code by grouping both the connections in one place and to keep my reads and inserts together so that I don't commit at the end of each insert etc. I don't seem to have the scope rules under control yet. Could you suggest how to improve this:
    import java.sql.*;
    public class Test_Combined2 {
    public static void main(String args[]) throws SQLException {
    // Load the Oracle JDBC driver
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    // Connect to the database
    // You must put a database name after the @ sign in the connection URL.
    // You can use either the fully specified SQL*net syntax or a short cut
    // syntax as <host>:<port>:<sid>. The example uses the short cut syntax.
    Connection con2 = DriverManager.getConnection ("jdbc:oracle:thin:@Test:1521:PSDEVElOP",
    "SOLOMON","SOL1");
    // Create a Statement
    Statement stmt2 = con2.createStatement ();
    String url = "jdbc:microsoft:sqlserver://INTRADEV:1433;DatabaseName=Measure";
    Connection con;
    String query = "select dataYear, dataMonth, yieldRate from tblYield " ;
    Statement stmt;
    try {
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
    } catch(java.lang.ClassNotFoundException e) {
    System.err.print("ClassNotFoundException: ");
    System.err.print(e.getMessage());
    // Select the ENAME column from the EMP table
    ResultSet rset = stmt2.executeQuery ("select year_start, monthofyear, percent_comp " +
    " from ps_usm_ytd_yield ");
    // Iterate through the result and print the employee names
    while (rset.next ()) {
    System.out.println (rset.getFloat (3));
    int ps_dataYear = rset.getInt(1);
    int ps_dataMonth = rset.getInt(2);
    float ps_yieldRate = rset.getFloat(3);
    try{
    con = DriverManager.getConnection (url, "tmpuser","tmppush");
    stmt = con.createStatement();
    PreparedStatement insertTblYield;
    String insertString = "insert into tblYield " +
    " values(?, ?, ?)";
    //con.setAutoCommit(false);
    insertTblYield = con.prepareStatement(insertString);
    insertTblYield.setInt(1, ps_dataYear);
    insertTblYield.setInt(2, ps_dataMonth);
    insertTblYield.setFloat(3, ps_yieldRate);
    insertTblYield.executeUpdate();
    con.commit();
    //con.setAutoCommit(false);
    /*ResultSet rs = stmt.executeQuery(query);
    System.out.println("dataYear, dataMonth, yieldRate");
    while (rs.next()) {
    int dataYear = rs.getInt(1);
    int dataMonth = rs.getInt(2);
    float yieldRate = rs.getFloat(3);
    System.out.println(" " + dataYear + ", " + dataMonth + ", " + yieldRate);
    stmt.close();
    con.close();
    } catch(SQLException ex) {
    System.err.print("SQLException: ");
    System.err.println(ex.getMessage());
    } //while
    stmt2.close();
    con2.close();

  • Toplink fails to connect using Datasource

    I'm deploying an EJB project using Toplink persistence to Oracle AS 10.1.3.1 and have defined a datasource/connection pool as:
    <managed-data-source name="OAS_Oracle_Datasource"
    connection-pool-name="My_Connection_Pool"
    jndi-name="jdbc/OAS_Oracle_Datasource"/>
    <connection-pool
         name="My_Connection_Pool"
         min-connections="3"
         max-connections="10">
    <connection-factory factory-class="oracle.jdbc.pool.OracleDataSource"
    user="joeuser"
    password="joepasswd"
    url="jdbc:oracle:thin:@dbserver:dev01">
    </connection-factory>
    </connection-pool>
    Once deployed I can test the datasource/connection pool successfully from the admin GUI. I can also access the database from an external client using the same connection parameters. However, I see this stack trace in log.xml:
    Exception [TOPLINK-4002] (TopLink (Oracle OC4J CMP) - 10g Release 3 (10.1.3.1.0) (Build 061004)): oracle.toplink.exceptions.DatabaseException
    Internal Exception: java.sql.SQLException: Io exception: The Network Adapter could not establish the connectionError Code: 17002
         at oracle.toplink.exceptions.DatabaseException.sqlException(DatabaseException.java:276)
         at oracle.toplink.internal.ejb.cmp.oc4j.Oc4jNonJtaConnector.connect(Oc4jNonJtaConnector.java:49)
         at oracle.toplink.sessions.DatasourceLogin.connectToDatasource(DatasourceLogin.java:147)
    <SNIP>
         at java.lang.Thread.run(Thread.java:595)
    Caused by: java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:138)
    <SNIP>
         at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:608)
         at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:218)
         at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPhysicalConnection(OracleConnectionPoolDataSource.java:114)
    <SNIP>
         at oracle.oc4j.sql.ManagedDataSource.getConnection(ManagedDataSource.java:197)
         at oracle.oc4j.sql.ManagedDataSource.getNonTransactionalConnection(ManagedDataSource.java:167)
         at oracle.oc4j.sql.ManagedDataSource.getNonTransactionalConnection(ManagedDataSource.java:153)
         at oracle.toplink.internal.ejb.cmp.oc4j.Oc4jNonJtaConnector.connect(Oc4jNonJtaConnector.java:44)
         ... 27 more
    Anyone run into this problem? If so please share your fix.
    Thanks,
    Gerald

    OK, a little more light shines on this mystery...
    It turns out that the deployer-generated orion-ejb-jar.xml was using a data-source attribute pointing at the jdbc/OracleDS datasource in the default application, which OAS creates during install. Of course this wasn't set to anything in particular, and if Toplink is using this behind the scenes it wouldn't connect.
    Now the question is how do I get my datasource stuffed into the auto-generated orion-ejb-jar.xml data-source? Would be nice if there was a way to specify some Toplink datasource property in the orion-ejb-jar.xml before it gets processed by the deployer into its eventual resting place under application-deplyments.
    Gerald

Maybe you are looking for

  • Trigger message without releasing PO

    Purchase order is subject to release strstergy. This is related to message out put type. My present setting for purchase order is one out put for sending to printer (ZNEU) and other one sending to third party software (ZBAD) by IDOC. Present working

  • Are the shared files accessible to a sony bluray player

    I have a Sony BluRay player that allows me to shared media from a Windows 7 PC.  Will the shared files located on an external hard drive attached to the Air Extreme be viewable on my Sony BluRay?

  • How to make Safari remember Zoom Lever

    I would like to load automaticly with a certain zoom level. When the page loads I have to constantly hit the command key then the + key so the page is large enough to read. I don't want to increase the font size but just to save this zoom level so ne

  • Announcing NoORM 1.0

    Hi, I would like to announce the availablity of our Open Source Java - ORM library and code generator "NoORM" 1.0 for Oracle. Everybody who looks for an efficient ORM - solution on top of JDBC, but thinks that JPA is too complex and cumbersome and do

  • How to make a column a key using CALL METHOD cl_salv_table= factory

    hy guys i have gotten everything right but cannot make a column of my internal table a key column done this so far for columns:   DATA: alv_columns_list    TYPE REF TO       cl_salv_columns_list.   DATA: alv_column     TYPE REF TO cl_salv_column.   a