JDBC CONNECTIONS RECURSIVE WAY

JAVA DEVELOPER COMUNITY
I request your help in the following topic,
i am doing a java program that store a
complete file system in an Oracle Database 11GR2.
So i use a recursive algorithm to do that
but i don't know how to handle the JDBC
connections in order to not overload the total of
physical connections available to the database.
Thanks for your help.
Regards from Colombia - South America
JOHN JAIRO GOMEZ LAVERDE
I am using the following code:
import java.io.* ;
import java.sql.*;
import java.lang.String;
import java.util.Date;
import java.util.Calendar;
import java.util.*;
import java.text.SimpleDateFormat;
import oracle.jdbc.*;
import oracle.jdbc.pool.*;
import javax.naming.*;
import javax.naming.spi.*;
public class InsertArcDir
public void AddFiles( File file )
try
Calendar fechamod=Calendar.getInstance();
String SQL;
PreparedStatement pstmt = null;
java.util.Properties prop = new java.util.Properties();
prop.setProperty("MinLimit", "2");
prop.setProperty("MaxLimit", "10");
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:@//oracle:1521/xe");
ods.setUser("hr");
ods.setPassword("hr");
ods.setConnectionCachingEnabled(true);
ods.setConnectionCacheProperties (prop);
//ods.getConnectionCacheName();
Connection conn = ods.getConnection ("hr","hr",prop);
Statement stmt = conn.createStatement();
fechamod.setTimeInMillis(file.lastModified());
SQL="INSERT INTO tbarchivos(nombrearc,fechaarc,direcarc) VALUES(?,?,?)";
pstmt = conn.prepareStatement(SQL);
java.sql.Timestamp sqlDate = new java.sql.Timestamp(fechamod.getTimeInMillis());
pstmt.setString(1, file.getName());
pstmt.setTimestamp(2, sqlDate);
pstmt.setString(3, file.getParent());
pstmt.executeUpdate();
stmt.close();
conn.close();
catch(Exception e)
System.out.println("Exepcion"+e.getMessage());
System.out.println("OTHER TEST");
* Works on a single file system entry and
* calls itself recursively if it turns out
* to be a directory.
* @param file A file or a directory to process
public void traverse( File file )
// Check if it is a directory
if( file.isDirectory() )
// Get a list of all the entries in the directory
String entries[] = file.list() ;
// Ensure that the list is not null
if( entries != null )
// Loop over all the entries
for( String entry : entries )
// Recursive call to traverse
traverse( new File(file,entry) ) ;
else
if(file.isFile())
InsertArcDir rta = new InsertArcDir() ;
rta.AddFiles(file);
else
System.out.println("*** VALOR INCORRECTO ***");
//try
//stmt.close();
//conn.close();
//catch(Exception e)
// System.out.println("Exepcion"+e.getMessage());
* The program starts here.
* @param args The arguments from the command line
public static void main( String args[] )
try
java.util.Properties prop = new java.util.Properties();
prop.setProperty("MinLimit", "2");
prop.setProperty("MaxLimit", "10");
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:@//oracle:1521/xe");
ods.setUser("hr");
ods.setPassword("hr");
ods.setConnectionCachingEnabled(true);
ods.setConnectionCacheProperties (prop);
ods.setConnectionCacheName("ImplicitCache01");
Connection conn = ods.getConnection ();
conn.close();
//Statement stmt = conn.createStatement();
// Create an object of this class
InsertArcDir rt = new InsertArcDir() ;
if( args.length == 0 )
// If there are no arguments, traverse the current directory
rt.traverse( new File(".") ) ;
else
// Else process every argument sequentially
for( String arg : args )
rt.traverse( new File(arg) ) ;
//stmt.close();
//conn.close();
catch(Exception e)
System.out.println("Exepcion"+e.getMessage());
*********************

I will not comment on weather or not to use recursion. However, I suggest:
This statement and its configuration should occur once in your program and not in a recursive function:
OracleDataSource ods = new OracleDataSource();
Assuming your using connection pooling, get a connection, use it, and close it as quickly as possible for each write to the database (not the best solution, but good enough for now until you read up on JDBC). Do not hold onto the connection for the duration of the application.
Conection pooling is designed to allow you to get and close a connection with minimal performance loss. I suggest reading up on JDBC, or better yet reading a book on JDBC.

Similar Messages

  • JDBC Connection taking way too long

    Hi,
    I have an odd problem which has just started to happen. I am creating a very simple JDBC connection to the MS SQL Server database using the Microsoft JDBC driver. This has always worked for me in the past and has never caused any problems. Now, however, creating a connection to my database is taking about 20 seconds! This is usually a sub-second operation. I have tried to narrow down the cause, but everything I have tried has failed. Here are all the things I have tried so far:
    1. Using a different JDBC driver (several, including the ODBC bridge)
    2. Create a test app which just has my connection code and run this from different machines on the network under different JDKs
    3. Re-installed by SQL Server database
    4. Connected using IP address rather than machine name (in case it was a DNS issue of some sort)
    5. Connected using different login accounts
    6. Vertified connectivity using telnet (port 1433)
    7. Verified connectivity via ODBC in an ASP page
    If I telnet to the SQL Server service I can connection without any delay. I can also connect immediately using an ODBC connection via an ASP page, so I don't think it's a problem with my database. I just seems that connectivity from Java land of woefully slow. I have never had this problem before, it's only started happening recently. The only thing that has changed recently is that I signed up for a new ADSL provider, but I can't see how this could have any bearing as all the machines are internal and connected by a 100Mbps router!
    Here's the code I am using to test...
    long current = System.currentTimeMillis();
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
    Connection connection = DriverManager.getConnection("jdbc:microsoft:sqlserver://<server-ip>:1433;User=<usr>;Password=<pwd>", null);
    System.out.println(System.currentTimeMillis() - current);
    connection.close();This gives me times of about 20 seconds.
    Help!

    You are right.. but the fact that:
    a) I can telnet and connect instantly
    b) The jdbc-odbc bridge connects immediately
    .. tells me that the network is ok.. at least for native functions. The only consistency I can find is that native (windows) functions connect without any issue, but pure Java functions experience problems. It may well be an issue with my network, but it seems that the issue is isolated to the Java environment (guessing here).
    I tested this theory by simply opening a socket connection from Java, but has not problems (connected immediately).
    I tried switching on the debug messages in the DriverManager (DriverManager.setLogWriter(writer))... this didn't tell me anything.
    ... The ONLY thing I can think of trying is disconnecting from my ADSL router and trying a simple cross-over cable from one machine to the other.
    Thanks for your help though.

  • Is there any way to set read timeout on JDBC connection?

    When the network connectivity between the machine
    where Database is running and where the application is running breaks,
    the query executed using the old connection handle is not timing out.
    Is there any way to set read timeout on JDBC connection. ?
    FYI, Oracle JDBC thin Driver is used in our application.

    Set the tuning parameters with Embedded OC4J Server Preferences>Current Workspace>Data Sources>jdev-connection-DBConnection1 node.
    Select the Tuning tab.
    The Inactivity Timeout parameter specifies the number of secs of inactivity after which a connection gets disconnected.

  • Error while creating a report that uses Oracle OCI JDBC connectivity

    Please let me know why my CR and LF characters are removed from my forum posting *****
    Hi,
    I was trying to create a report that uses Oracle OCI JDBC connectivity. I am using Eclipse3.4 download from "cr4e-all-in-one-win_2.0.2.zip".  I have successfully created a JDBC OCI connection.
    The connection parameters are given below:
    URL: jdbc:oracle:oci8:@xe
    Database: xe
    username: <userName>
    password: <password>
    I have tested the above connection in Data source Explorer and it works fine!!!
    But I am getting the following error when I drag-and-drop a table from the list of tables. Not sure what I am missing here?  Any help is highly appreciated.
    com.businessobjects.reports.jdbinterface.common.DBException: InvalidURLOrClassName
         at com.crystaldecisions.reports.queryengine.driverImpl.jdbc.JDBCConnection.Open(Unknown Source)
         at com.crystaldecisions.reports.queryengine.JDBConnectionWrapper.Open(SourceFile:123)
         at com.crystaldecisions.reports.queryengine.Connection.br(SourceFile:1771)
         at com.crystaldecisions.reports.queryengine.Connection.bs(SourceFile:491)
         at com.crystaldecisions.reports.queryengine.Connection.t1(SourceFile:2979)
         at com.crystaldecisions.reports.queryengine.Table.u7(SourceFile:2408)
         at com.crystaldecisions.reports.dataengine.datafoundation.AddDatabaseTableCommand.new(SourceFile:529)
         at com.crystaldecisions.reports.common.CommandManager.a(SourceFile:71)
         at com.crystaldecisions.reports.common.Document.a(SourceFile:203)
         at com.businessobjects.reports.sdk.requesthandler.f.a(SourceFile:175)
         at com.businessobjects.reports.sdk.requesthandler.DatabaseRequestHandler.byte(SourceFile:1079)
         at com.businessobjects.reports.sdk.JRCCommunicationAdapter.do(SourceFile:1163)
         at com.businessobjects.reports.sdk.JRCCommunicationAdapter.if(SourceFile:657)
         at com.businessobjects.reports.sdk.JRCCommunicationAdapter.a(SourceFile:163)
         at com.businessobjects.reports.sdk.JRCCommunicationAdapter$2.a(SourceFile:525)
         at com.businessobjects.reports.sdk.JRCCommunicationAdapter$2.call(SourceFile:523)
         at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
         at java.util.concurrent.FutureTask.run(Unknown Source)
         at com.businessobjects.crystalreports.designer.core.util.thread.ExecutorWithIdleProcessing$3.doWork(ExecutorWithIdleProcessing.java:182)
         at com.businessobjects.crystalreports.designer.core.util.thread.AbstractCancellableRunnable.run(AbstractCancellableRunnable.java:69)
         at com.businessobjects.crystalreports.designer.core.util.thread.PriorityTask.run(PriorityTask.java:75)
         at com.businessobjects.crystalreports.designer.core.util.thread.PriorityCompoundCancellableRunnable.runSubtask(PriorityCompoundCancellableRunnable.java:187)
         at com.businessobjects.crystalreports.designer.core.util.thread.PriorityProgressAwareRunnable.runSubtask(PriorityProgressAwareRunnable.java:90)
         at com.businessobjects.crystalreports.designer.core.util.thread.PriorityCompoundCancellableRunnable.doWork(PriorityCompoundCancellableRunnable.java:144)
         at com.businessobjects.crystalreports.designer.core.util.thread.AbstractCancellableRunnable.run(AbstractCancellableRunnable.java:69)
         at com.businessobjects.crystalreports.designer.core.util.thread.ExecutorWithIdleProcessing$IdleTask.run(ExecutorWithIdleProcessing.java:320)
         at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Thanks
    Karthik
    Edited by: KARTHIK1 on Oct 14, 2009 9:38 PM

    Hi Ted,
    Thanks for the feedback. I was able to create a report in Creystal Reports Designer 2008 using OCI.  It is not allowing only in the Eclipse plugin. In our environment we are not allowed to user Oracle thin connections and ONLY OCI is allowed.
    1) Can you please let me know if there is a way to do this? 
    2) Will it allow data sources using native database driver?
    3) If so, can I use JRC to create these reports from a desktop java program?
    Thanks & Regards
    Karthik
    Edited by: KARTHIK1 on Oct 15, 2009 4:38 PM

  • How to use JDBC Connection Pools in a standalone application?

    Hi, there,
    I have a question about how to use JDBC Connection Pools in an application. I know well about connection pool itself, but I am not quite sure how to keep the pool management object alive all the time to avoid being destroyed by garbage collection.
    for example, at the website: http://www.developer.com/java/other/article.php/626291, there is a simple connection pool implementation. there are three classes:JDBCConnection, the application's gateway to the database; JDBCConnectionImpl, the real class/object to provide connection; and JDBCPool, the management class to manage connection pool composed by JDBCConnectionImpl. JDBCPool is designed by Singleton pattern to make sure only one instance. supposing there is only one client to use connection for many times, I guess it's ok because this client first needs instantiate JDBCPool and JDBCConnectionImpl and then will hold the reference to JDBCPool all the time. but how about many clients want to use this JDBCPool? supposing client1 finishes using JDBCPool and quits, then JDBCPool will be destroyed by garbage collection since there is no reference to it, also all the connections of JDBCConnectionImpl in this pool will be destroyed too. that means the next client needs recreate pool and connections! so my question is that if there is a way to keep pool management instance alive all the time to provide connection to any client at any time. I guess maybe I can set the pool management class as daemon thread to solve this problem, but I am not quite sure. besides, there is some other problems about daemon thread, for example, how to make sure there is only one daemon instance? how to quit it gracefully? because once the whole application quits, the daemon thread also quits by force. in that case, all the connections in the pool won't get chance to close.
    I know there is another solution by JNDI if we develop servlet application. Tomcat provides an easy way to setup JNDI database pooling source that is available to JSP and Servlet. but how about a standalone application? I mean there is no JNDI service provider. it seems a good solution to combine Commons DBCP with JNID or Apache's Naming (http://jakarta.apache.org/commons/dbcp/index.html). but still, I don't know how to keep pool management instance alive all the time. once we create a JNDI enviroment or naming, if it will save in the memory automatically all the time? or we must implement it as a daemon thread?
    any hint will be great apprieciated!
    Sam

    To my knoledge the pool management instance stays alive as long as the pool is alive. What you have to figure out is how to keep a reference to it if you need to later access it.

  • ADF: Gracefully handling JDBC connection errors?  Part II

    Hi gang
    I while back I posted a forum post to find a solution to "display a specific web page when the JDBC connection drops out on our ADF application, specifically the following error: oracle.jbo.DMLException: JBO-26061: Error while opening JDBC connection"
    ...you can see the original post here:
    Re: ADF: Gracefully handling JDBC connection errors?
    For the life of me I can't get this to work now. It appears I can't redirect to another page during the call to reportException. I've had a play with different methods of redirecting, as seen in the following code sample:
    public class ErrorHandlerImpl extends DCErrorHandlerImpl {
      public ErrorHandlerImpl() {
        super(true);
      @Override
      public void reportException(DCBindingContainer dCBindingContainer, Exception exception) {
    //    try {
          String message = exception.getMessage();
          if (message.indexOf("JBO-26061") >= 0) {
            // Method 1
            FacesContext fc = FacesContext.getCurrentInstance();
            UIViewRoot viewRoot =
            fc.getApplication().getViewHandler().createView(fc, "faces/errorPage.jspx");
            fc.setViewRoot(viewRoot);
            fc.renderResponse();
            // Method 2              
            // FacesContext fc = FacesContext.getCurrentInstance();
            // fc.getApplication().getNavigationHandler().handleNavigation(fc, null, "goError");
            // fc.responseComplete();
            // Method 3 - required IOExcepition handler
            // FacesContext.getCurrentInstance().getExternalContext().redirect("faces/errorPage.jspx");
          } else
              super.reportException(dCBindingContainer, exception);
    //    } catch (IOException e) {
    }... with no success.
    Has anyobody any other solutions or advice on getting this to work?
    Your help appreciated.
    Thanks & regads,
    CM.
    PS. JDev 11gR1 ADF BC + ADF Faces RC

    Hi Frank
    Yep, I' tried redirect, that was method 3 (you can see all 3 methods I've attempted, last 2 are commented out).
    With the declarative ADFc exception handler, problem is it's a catch all, not specifically for JBO-26061. Can you think of a way I can tailor fit it for JBO-26061 with a custom message "Database down"?
    In addition the exception handler is not consistently called. As example, if you're moving between pages rather than operating on 1 page, the standard af:messages error dialog is shown if the db connection has been dropped, rather than navigating to the exception handler page. As such it seems the DCErrorHandlerImpl.reportExceptions is the better chokepoint to work from.
    Cheers,
    CM.

  • Can not deploy a report using JDBC connection on CR2008 Server

    Hi Group,
    I have a report created with JDBC connection. When I tried to add it to CR2008 server, it gives an error - "An unexpected error has occurred ". Basically I want to add a report to a public folder via CMC. I am using adminstrator account.
    Then I thought I need to add JDBC driver into CR2008 server. so I put oracle jdbc jar into CR2008 server classpath and add JDBC connection info into CRConfig.xml. but I still got the same error.
    I also tried:
    - Change the report to use native Oracle driver rather than JDBC. The deployment succeeded (but this is not what I want)
    - Add a data source connection via Business View Manager, but no luck.
    I know how to use/change jdbc connection with programtic way, but I just want to know if I want to use built-in components in CR2008 server without any coding the reports can be deployed and managed.
    Thanks in advance.
    Dennis

    Hello Will,
    Crystal Reports supports connections to JDBC/JNDI out of the box, and have done so for a while, whether stand-alone or published to Enterprise.
    To specify where the server would search for the JDBC driver jar files, you'd change the classpath tag found in the CRConfig.xml file found on the machine where the Crystal Reports Page or Job Server is running. 
    For early Crystal Enterprise 10 and before, it used Java Native Interface (JNI) to start the Java process to retrieve the data from the JDBC connection.
    For later Crystal Enterprise 10 and later, it starts off a "Java Server" process, and communicates to the Crystal Reports process via CORBA TCP/IP connection.
    Commonissues that may arise:  (1) CRConfig.xml not configured properly, (2) unable to start or communicate to the "Java Server" because of permissions or firewall.
    Note that this is a separate connectivity map from using ADO or ADO.NET.
    Sincerely,
    Ted Ueda

  • How to set roles from JDBC connections

    Hi guys,
    I have a jdbc connection which purpose is to run queries based on a string that I construct in my program.
    My question is: if I have to run a DCL, like: SET ROLE RL_XXX TO USER1;
    What's the easiest way to do it with my same connection?
    Thanks.

    Hi Marc,
    Sorry for the typo. It's a BDC source, I use a WCF client to access a SQL Database (HR External System) that has 4 fields that are necessary to present in the Sharepoint User Profile. The issue occurs with a Full or a Delta Sync. The problem is that if the
    BDC source is not present the fields are deleted (I get a SPS-Dummy Added and all of the pbjects in the BDC Connector Space are deleted).
    I do not want this to happen. I do not want the User Profile Attributes/Fields to be empty/deleted if there is no connection I simply want them to stay what they are... I have two issues.
    1) Is that the even if i change my data on SQL Server side, the changes do not get picked up by the sync. Since the only field that is being tested for change is an ADid, since the id does not change the BDC does not consider them changes.
    2) If there is no connection I do not want the attributes to be deleted. I have not figured out a way to effectively do this.
    So my issue appears to be simple to solve, but after 4 days and hundreds of tutorial pages read I have yet to figure out a proper way to do this.
    Here is the pseudo-specification
    The Fields that come form the HR System (SQL Server) are to be presented in the user profile. If there is no connection to the BDC file the fields remain as they are until there is a connection and updates can be made. Changes to any of the fields are performed
    manually in the HR system. These changes must be picked up by the daily sync.

  • Deployed application can't see the JDBC connection

    Hi
    I made an ADF application using oracle JDeveloper 11g and it ran successfully from the JDeveloper
    I deployed it to Weblogic 10.3 and it successfully deployed
    But when i Opened the deployed application's URL the page's lay out is only what i c (only the template) with the following error:
    =================================================
    Error while opening JDBC connection.
    ORA-01005: null password given; logon denied
    Unexpected exception caught: java.lang.NullPointerException, msg=null
    =================================================
    SO, how could I make my application c the JDBC ?
    by the way when i created the DB connection in the JDeveloper i checked(deploy password)

    Hi Eddy
    I got the same problemas you posted.now i changed the configurations of AMlocal.i changed from JDBC URL to JDBC datasource.
    i saved the changes. i created a new EAR and deployed to external WLS 10.3 from Jdev11.1.1
    when i am testing tha app from external WLS,i am getting the following error
    JNDI failure.unable to lookup DataSource at context
    java:comp/env/jdbc/Connection1DS
    while trying to lookup'jdbc.Connectiobb1DS' didn't find
    subcontext 'jdbc'.Resolved"
    Unexpected exception caught:
    java.lang.NullpointerException,msg=null
    Can you tell me where the problem is?

  • Secure JDBC Connection

    Our application uses JDBC to connect to Sybase, Oracle and MSSQL databases. I do not see any way to encrypt the password. But the machine has IPSec installed. My questions are:
    Is the JDBC connection considered secure with IPSec installed
    If so, doe IPSec has to exist on both source and destination machines.

    LarryY wrote:
    Our application uses JDBC to connect to Sybase, Oracle and MSSQL databases. I do not see any way to encrypt the password. But the machine has IPSec installed. My questions are:
    Is the JDBC connection considered secure with IPSec installed The IP traffic would be secure.
    Whether that is good enough depends on your security policy and business needs.
    If so, doe IPSec has to exist on both source and destination machines.Of course.
    IPSec of course will require that you mandate the use of it. You will have no control of it in your code. You won't even be able to detect it.
    Obviously finding secure drivers would allow you to insure it at the code level.

  • JDBC Connection for Oracle

    Hello Experts,
    I'm having some trouble getting a JDBC connection to work correctly and I am in need of some advice.
    Background:
    I have setup a test Portal 7.00 SP14 with an Oracle 10.2.0.2.0 database on a Windows 2003 X64 server.  The Portal system was up and running and connecting to a WAS6.20 systems.  We do not have BI or XI in our landscape.
    I needed to connect to an Oracle 10.2.0.3.0 database from visual composer to read some data from tables to do a proof of concept. From what I understand this connection will be a JDBC connection.  I have setup a new system using the JDBC template, assisnged an alias, and entered the connection URL .  I was unable to connect. 
    I read that I need to add the driver using Visual Composer.  I did so with the following instructions:
    Install JDBC Driver
    • Start the Visual Administrator
    • Logon at WebAS
    • Open: Server, Services, JDBC Connector, Drivers
    • Choose “Create New Driver or DataSource” on the toolbar
    • Specify an arbitrary name for your driver entry such as “OracleDriver” and click OK
    • Now search for the Oracle JDBC Driver JAR file on your local harddisk.
    I restarted the Java instance with SMICM after completing this task Java will not start.  Is there anyway to roll back that change to get Java back up and running? 
    Also is there a better way to go about making this oracle connection?
    Best Regards,
    Edited by: Troy Loseke on Feb 20, 2008 8:30 AM

    Hi,
    although [this guide|https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/92d80512-0a01-0010-32a3-cd3735bd9275] is for Visual Composer I find it very helpful in setting up JDBC connections to databases. There is a very deltailed section about setting up a system to a MS SQL Server and the relevant data if you want to connect to Oracle:
    4.2 BI JDBC Connector to Oracle
    Located at:
    http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html
    Driver: oracle.jdbc.driver.OracleDriver
    URL: jdbc:oracle:<drivertype>:@<database>
    jdbc:oracle:thin:@myhost:1521:orcl
    Hope this helps,
    Holger.

  • View # of current Connection of jdbc connection pool

    Do you guy know of ANY METHODS of viewing # of current database Connection of jdbc connection pool in SUNAPP SERVER?
    for example i have jdbc/Dashboard Connection Pool in SUNAPP SERVER and I wanted to view, at any point of time, how many connection database that it is being utilized during that time. The reason I wanted to see the # of currection jdbc connection is because my Max (400connections) ran out or hanging really long period of time.
    Thanks,
    Kelvin

    There is no way currently to do this

  • How to fix jdbc connection when  SQLstate 08S01

    I have an application that connects to and insert into a remote database which runs on a server I connect to over the internet. I tested it on local server (localhost) and it works fine, but when I put my server IP (72.52.155.111) or web domain I can' t connect. I'm not sure what should I write instead localhost: webdomain or something else ?
    Java code...
    conn =   DriverManager.getConnection("jdbc:mysql://72.52.155.111:3306/fritaor_apartmani" ,"fritaor_root","10000000");
    ...Error code:
    SQLException: Communications link failure due to underlying exception:
    ** BEGIN NESTED EXCEPTION **
    java.net.SocketException
    MESSAGE: java.net.ConnectException: Connection timed out: connect
    STACKTRACE:
    java.net.SocketException: java.net.ConnectException: Connection timed out: conne
    ct
            at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.ja
    va:156)
            at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:276)
            at com.mysql.jdbc.Connection.createNewIO(Connection.java:2666)
            at com.mysql.jdbc.Connection.<init>(Connection.java:1531)
            at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java
    :266)
            at java.sql.DriverManager.getConnection(Unknown Source)
            at java.sql.DriverManager.getConnection(Unknown Source)
            at Mysql.save(Mysql.java:57)
            at Contact.run(Contact.java:299)
            at Testing.main(Testing.java:21)
    ** END NESTED EXCEPTION **
    Last packet sent to the server was 47 ms ago.
    SQLState: 08S01
    VendorError: 0

    Try to connect to the server in another way (such as telnet). See if you can connect to port 3306. If not, the port is blocked or there's nobody listening (is there a mysql server running on the host?).

  • Jdbc connection in EJB using wsad 5.0

    Hi,
    I want to develop a small application using Ejbs by using oracle 9i as D/b, wsad 5.0 as app server . The problem is i am not able to connect to oracle database in WSAD. What i am doing is i have installed Oracle 9i in my system and has given the Global database name as "samp" while installation . I open my SQL plus with username scott and password tiger and i am able to do all my sql queries successfully.
    Now coming to WSAD,
    while creating a JDBC connection using Oracle 9i driver,
    i ve opened in Data perspective and in that go to DB Servers -> Right click -> New Connection
    There a window is opened for Database Connection.
    We need to fill the fields there.
    I have given samp as Global d/b name while installing Oracle 9i .
    In the window , the feilds are
    Connection Name : conn
    Database Name : samp
    user id : scott
    password : tiger
    D/b vendor type: Oracle 9i
    Jdbc Driver : Oracle Thin Driver
    Host : 127.0.0.1
    port No: 1521
    class location : c:\oracle\ora90\jdbc\lib\classes12.zip
    connection url : jdbc:oracle:thin:@127.0.0.1:1521:samp
    the class location and connection url are automatically coming.
    and please check whether all fields are correct or not
    Is this the correct way.
    Next in code if i want to connect to database should i use connection establish commands again or i can directly use create statement or prepare statement.
    Please reply.
    Thanks

    Create New Server and configure it properly
    It will work
    procedure is as follows:
    Pls visit the following link:
    http://www.webagesolutions.com/knowledgebase/waskb/waskb001/index.html
    Adding a Oracle9i DataSource from WSAD5
    Bibhas Bhattacharya, Web Age Solutions Inc.
    Before you begin, make sure that you have Oracle installed and a database is created. In this document we will use a database called MALL.
    Create a WAS V5 Server
    If you don't already have a WebSphere V5 server created, do so following these steps. Switch to the Server perspective. Right click in the Server Configuration view and select New->Server and Server Configuration.
    Name the server WASV5. Make sure that the Server type is set to WebSphere version 5.0->Test Environment. Click on Finish.
    Add the Database User
    In WSAD5, the default user ID and password to be used by a DataSource are first entered as a JAAS authentication entry.
    In the Server Configuration view, double click on WASV5 to open the configuration editor. Click on the Security tab. Next to the JAAS Authentication Entries list click on Add and add the user.
    Add the JDBC Driver
    Still in the server configuration GUI click on the DataSource tab. You can add the DataSource at the server level or at the node level. We will add it at the server level. Make sure that the Server Settings is expanded. Next to the JDBC providers list click on Add.
    Select the following options:
    Database type: Oracle
    JDBC provider type: Oracle JDBC Thin Driver or the XA version of it if you need two phase commit transaction.
    Click on Next.
    Set the name to Oracle Thin Driver.
    Notice that the location of the driver's class is automatically set to ${ORACLE_JDBC_DRIVER_PATH}/classes12.zip. Here, ORACLE_JDBC_DRIVER_PATH is a node level variable. We need to make sure that the variable is pointing to the correct directory where Oracle's JDBC driver is installed. In our case, we had installed Oracle in c:\oracle. This had installed the JDBC driver class in C:/oracle/ora81/jdbc/lib/classes12.zip.
    In the server configuration GUI click on the Variables tab. Under the Node settings select ORACLE_JDBC_DRIVER_PATH from the Defined variables list. Click on Edit and set the value to C:/oracle/ora81/jdbc/lib.
    Add the DataSource
    Click on the DataSource tab again. Select the Oracle Thin Driver you had created in the previous step. Click on Add next to the Data source defined in the JDBC provider selected above list.
    Select the following options:
    Select the type of JDBC Driver: Oracle JDBC Thin Driver.
    Select the data source type: Unless you will be testing your application with WAS V4, select Version 5.0. You can not use a V4 DataSource from a J2EE 1.3 EJB module running in WebSphere V5.
    Click on Next.
    Enter these key attributes in this screen:
    Name: My Oracle DataSource
    JNDI Name: jdbc/MyDataSource
    DataSource helper class name: com.ibm.websphere.rsadapter.OracleDataStoreHelper. Should be selected by default. The helper class is needed if you wish to access IBM extensions to JDBC. For more details search in WSAD help for "WSDataSource interface".
    Component-managed authentication alias: Set this if you wish to lookup the DataSource using its global JNDI name or using the java:comp/env/ name space and have set the authentication type of the resource reference to Application. Select the JAAS entry you had created. That is, Database user.
    Container-managed authentication alias: Set this if you intend to lookup the DataSource using the java:comp/env/ name space and have set the authentication type of the resource reference to Container. Select the JAAS entry you had created. That is, Database user.
    Use this data source in container managed persistence (CMP): Check on if you intend to use the DataSource from CMP EJBs.
    Click on Next.
    You need to set these properties:
    databaseName: MALL in our case.
    URL: jdbc:oracle:thin:@noble.webagesolutions.com:1521:MALL. In my case the server host name is noble.webagesolutions.com. The listener port number is 1521 (usually the default in most Oracle installations).
    Click on Finish.
    You have finished adding the DataSource. Save the server settings by clicking Control+S. Close the server configuration GUI.
    Testing the DataSource
    There is no out of the box way to test the DataSource. You can create a simple Servlet and add the following code:
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
    javax.sql.DataSource ds = null;
    java.sql.Connection con = null;
    java.io.PrintWriter out = resp.getWriter();
    resp.setContentType("text/html");
    try {
    out.println("Looking up DataSource<br>");
    javax.naming.InitialContext ctx = new javax.naming.InitialContext();
    ds = (javax.sql.DataSource) ctx.lookup("jdbc/MyDataSource");
    out.println("Getting connection<br>");
    con = ds.getConnection();
    con.close();
    } catch (Exception e) {
    e.printStackTrace(out);
    out.println("Done<br>");
    Feedback
    Your e-mail:
    Rate this article:
    Very useful Somewhat useful Not bad Needs many corrections
    Comments:

  • Obtaining an oracle.sql.STRUCT through a pooled JDBC connection

    Hello,
    I am using WebLogic Server 10 and and Oracle 10 and I am trying to obtain a vendor-specific oracle.sql.STRUCT from a ResultSet using a pooled connection defined in Weblogic. I need the vendor-specific object, rather than simply the java.sql.Struct implementation, because a third party library requires it.
    What gets returned in the ResultSet is a non-exposed WebLogic wrapper object which implements java.sql.Struct, but which cannot be cast to an oracle.sql.STRUCT. I can use reflection on this object to find and call the getVendorObj() method to obtain the oracle.sql.STRUCT, but this solution is not acceptable because this is not a published API and is not guaranteed not to change in future versions.
    How can I reliably obtain a vendor-specific implementation of java.sql.Struct through a WebLogic connection pool in WebLogic Server 10?
    Thanks for any advice,
    -Dan Schwemlein

    dan schwemlein wrote:
    Joe,
    Thanks again. With your guidance, I have arrived at the following approach, which I'll post for the benefit of others, and which I'd be thankful if you would validate:
    1) Import the jar com.bea.core.datasource-1.0.0.0.jar from %BEA_HOME%\modules, which is the only location of the class WLConnection, which is the only class with the getVendorConnection() method you refer to.
    2) Get the logical connection from the pooled data source, cast it to a WLConnection, call getVendorConnection() to obtain an OracleConnection (from the ojdbc jar), and use this connection to obtain the required oracle.sql.STRUCT from an OracleResultSet.
    3) Be aware of the limitations and follow the guidelines in the document http://e-docs.bea.com/wls/docs81/jdbc/thirdparty.html#1043646 regarding security, error handling, releasing resources (close only the logical connection), etc.
    Does this sound like the approach you had in mind?
    Thanks again,
    -Danyes.
    Joe
    >
    Re: Obtaining an oracle.sql.STRUCT through a pooled JDBC connection
    Posted: Jul 16, 2007 3:21 PM
    dan schwemlein wrote:
    Thanks for the quick response!I was working today...
    Thank you for the information about the connection being closed.
    I will look into using this configuration setting.
    You say that you can describe a way to get a handle on an unwrapped
    pool object using some documented WLS-specific code. Are you referring
    here to the getVendorConnection() method?yes.
    This method does not help me
    get the oracle.sql.STRUCT object, because even the connection returned
    by getVendorConnection() returns a wrapped WL java.sql.Struct object
    from a call to getObject().I don't believe it. If you are running in WLS, with a local pool,
    the getVendorConnection() will give you the Oracle connection,
    which will give you an Oracle statement, etc, down to an oracle
    STRUCT object. Once you have a direct reference to the oracle connection,
    we're not in the picture when it returns something to you.
    It would be great if getVendorObj() were
    documented and could be counted on in future versions. To use this
    method, one would still have to access it via Java reflection, because
    the wrapper class and its getVendorObj() method would be exposed in an
    API, correct? Could this method be exposed in the API, so that reflection
    doesn't need to be used, or it is exposed somewhere that isn't documented?getVendorObj() is not yet exposed or therefore supported for the general
    wrapped object, so you would have to start from the connection and
    derive all subobjects from it.
    Thanks again,
    -Dan Schwemlein
    Hello,
    I am using WebLogic Server 10 and and Oracle 10 and I am trying to obtain a
    vendor-specific oracle.sql.STRUCT from a ResultSet using a pooled connection
    defined in Weblogic. I need the vendor-specific object, rather than simply
    the java.sql.Struct implementation, because a third party library requires it.
    What gets returned in the ResultSet is a non-exposed WebLogic wrapper object
    which implements java.sql.Struct, but which cannot be cast to an oracle.sql.STRUCT.
    I can use reflection on this object to find and call the getVendorObj() method to
    obtain the oracle.sql.STRUCT, but this solution is not acceptable because this is
    not a published API and is not guaranteed not to change in future versions.Understood. We all benefit from sticking to the J2EE standards,
    but we could also wish Oracle had done so with it's driver objects.
    I will assume your code is running in the WebLogic server, because
    an external JVM can never access the real driver object, which will
    always really be in the WLS JVM. No active JDBC object is serializable.
    How can I reliably obtain a vendor-specific implementation of java.sql.Struct
    through a WebLogic connection pool in WebLogic Server 10?There is no way to get a handle on an unwrapped pool object without using some
    WLS-specific code, though I can describe a way with documented methods,
    and/or I can get our documentation altered to say we'll support the
    getVendorObj() method. We introspect every vendor object, and for those
    implementations that have done the wise thing, projecting any non-standard
    methods as an Interface, we are able to also project that Interface so
    the vndor example code should work. However, in some poorly-done
    cases, such as for some Oracle stuff, there is either no Interface,
    or the Oracle code has extensions that take java.sql objects as input,
    (at least that's the signature of the method) but two lines into the
    method, the Oracle code assumes and casts the java.sql object to a concrete
    Oracle object. In these use cases you need the direct unwrapped object.
    We provide and document Connection.getVendorConnection(), and intend
    getVendorObj() to serve the same for subobjects, but note the dangers
    and responsibilities: We rely on our wrappers to implement the security
    and thread-safety of our pooling system. Because user code can get
    unrestricted access to the actual connection from most JDBC objects,
    we can never trust that we have complete control once a vendor object
    is exposed. Therefore, by default we will close and replace every JDBC
    connection so exposed, as soon as the current thread is finished with
    the pool connection. This hurts performance. We also document a pool
    config setting that will tell us that you take responsibility for any such
    problems, and not to close connections just because they've been exposed.
    HTH,
    Joe
    Thanks for any advice,
    -Dan Schwemlein

Maybe you are looking for