简体   繁体   中英

getting database connection in java hangs

Writing a program to determine management level ID's from a database. I've used this same connection method through the site over and over but it doesn't hang anywhere else. However, those methods aren't buried within an actual class. Is there any reason why putting this particular code into a java class would make it hang?

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
import oracle.jdbc.driver.OracleDriver;
import java.sql.*;

public class connection 
{  

  public Connection getDBConnection()
  {
     java.sql.Connection conn=null;

     try
     {
        DriverManager.registerDriver(new OracleDriver());
        conn = DriverManager.getConnection("stuff"); //Hangs here for like 2 seconds

     }
        catch (Exception e)
        {
           e.printStackTrace();
        }

     return conn;       
  }
}

Just to reiterate, I use this via a straight up jsp (no classes in that jsp) throught the site, but for this particular segment, I implemented it as a method within a class. This seems to be the only place where it hangs. Also, if you could give me the specific imports to make the database connection work so I can get rid of some of those ".*"...that would be awesome. Thanks

Edit: For more clarity, I create object X and in object X it creates the connection class object which calls this method.

So,

 someClass whatever = new someClass(); 
 Connection conn = null; 
 conn = whatever.getDBConnection(); //hangs

Are you pooling the connections in other places? If you are creating the new connection each time then it could likely take a couple seconds.

Also, why are you always registering the OracleDriver?

You should only register the driver once.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
import oracle.jdbc.driver.OracleDriver;
import java.sql.*;

public class connection 
{  
  static {
      try {
         DriverManager.registerDriver(new OracleDriver());
      }
      catch (SQLException excep) { // log exception }
  }


  public Connection getDBConnection()
  {
     java.sql.Connection conn=null;

     try
     {
        conn = DriverManager.getConnection("stuff"); //Hangs here for like 2 seconds

     }
        catch (Exception e)
        {
           e.printStackTrace();
        }

     return conn;       
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM