Jdbc err

Can anybody what does this messahe mean
Error while parsing or executing XML-SQL document: Error processing request in sax parser: Error when executing statement for table/stored proc. 'SKUMASTER' (structure 'insert'): java.sql.SQLException: FATAL ERROR document format: structure 'insert', no key element found
Thanx.. Vinithra

Hi Vinitha,
You need to check this link:
[Document Format for Receiver Adapter.|http://help.sap.com/saphelp_nw2004s/helpdata/en/2e/96fd3f2d14e869e10000000a155106/content.htm]
Make sure @action is INSERT, not UPDATE_INSERT.
You structure must be something like this:
<StatementName2>
<dbTableName action=u201DINSERTu201D>
<table>realDbTableName</table>
<access>
<col1>val1</col1>
<col2>val2</col2>
</access>
<access>
<col1>val11</col1>
</access>
</dbTableName> 
</StatementName2>
Regards

Similar Messages

  • SQL server 2000 setup

    I am unable to configure JBoss to the SQL Server 2000.
    I keep getting these errors when i deploy a jar file:
    17:18:15,234 INFO [EjbModule] Creating
    17:18:15,250 INFO [EjbModule] Deploying CustomerEJB
    17:18:15,390 INFO [EjbModule] Created
    17:18:15,390 INFO [EjbModule] Starting
    17:18:17,609 WARN [ServiceController] Problem starting service jboss.j2ee:jndiN
    ame=MSSQLDS,service=EJB
    org.jboss.deployment.DeploymentException: Error while fixing table name; - neste
    d throwable: (org.jboss.util.NestedSQLException: Could not create connection; -
    nested throwable: (java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for
    JDBC]Error establishing socket.); - nested throwable: (org.jboss.resource.Resour
    ceException: Could not create connection; - nested throwable: (java.sql.SQLExcep
    tion: [Microsoft][SQLServer 2000 Driver for JDBC]Error establishing socket.)))
    at org.jboss.ejb.plugins.cmp.jdbc.SQLUtil.fixTableName(SQLUtil.java:67)
    at org.jboss.ejb.plugins.cmp.jdbc.bridge.JDBCEntityBridge.<init>(JDBCEnt
    ityBridge.java:103)
    at org.jboss.ejb.plugins.cmp.jdbc.JDBCStoreManager.initStoreManager(JDBC
    StoreManager.java:397)
    at org.jboss.ejb.plugins.cmp.jdbc.JDBCStoreManager.start(JDBCStoreManage
    r.java:339)
    at org.jboss.ejb.plugins.CMPPersistenceManager.start(CMPPersistenceManag
    er.java:198)
    at org.jboss.ejb.EntityContainer.start(EntityContainer.java:376)
    at org.jboss.ejb.Container.invoke(Container.java:756)
    at org.jboss.ejb.EntityContainer.invoke(EntityContainer.java:1058)
    at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:517)
    at org.jboss.system.ServiceController$ServiceProxy.invoke(ServiceControl
    ler.java:978)
    at $Proxy5.start(Unknown Source)
    at org.jboss.system.ServiceController.start(ServiceController.java:398)
    at sun.reflect.GeneratedMethodAccessor7.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
    sorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at org.jboss.mx.capability.ReflectedMBeanDispatcher.invoke(ReflectedMBea
    nDispatcher.java:284)
    at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:517)
    at org.jboss.util.jmx.MBeanProxy.invoke(MBeanProxy.java:174)
    at $Proxy20.start(Unknown Source)
    at org.jboss.ejb.EjbModule.startService(EjbModule.java:430)
    at org.jboss.system.ServiceMBeanSupport.start(ServiceMBeanSupport.java:1
    65)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
    java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
    sorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at org.jboss.mx.capability.ReflectedMBeanDispatcher.invoke(ReflectedMBea
    nDispatcher.java:284)
    at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:517)
    at org.jboss.system.ServiceController$ServiceProxy.invoke(ServiceControl
    ler.java:978)
    at $Proxy5.start(Unknown Source)
    at org.jboss.system.ServiceController.start(ServiceController.java:398)
    at sun.reflect.GeneratedMethodAccessor7.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
    sorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at org.jboss.mx.capability.ReflectedMBeanDispatcher.invoke(ReflectedMBea
    nDispatcher.java:284)
    at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:517)
    at org.jboss.util.jmx.MBeanProxy.invoke(MBeanProxy.java:174)
    at $Proxy9.start(Unknown Source)
    at org.jboss.ejb.EJBDeployer.start(EJBDeployer.java:395)
    at org.jboss.deployment.MainDeployer.start(MainDeployer.java:807)
    at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:621)
    at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:585)
    at sun.reflect.GeneratedMethodAccessor13.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
    sorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at org.jboss.mx.capability.ReflectedMBeanDispatcher.invoke(ReflectedMBea
    nDispatcher.java:284)
    at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:517)
    at org.jboss.util.jmx.MBeanProxy.invoke(MBeanProxy.java:174)
    at $Proxy4.deploy(Unknown Source)
    at org.jboss.deployment.scanner.URLDeploymentScanner.deploy(URLDeploymen
    tScanner.java:435)
    at org.jboss.deployment.scanner.URLDeploymentScanner.scanDirectory(URLDe
    ploymentScanner.java:656)
    at org.jboss.deployment.scanner.URLDeploymentScanner.scan(URLDeploymentS
    canner.java:507)
    at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.
    doScan(AbstractDeploymentScanner.java:212)
    at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.
    loop(AbstractDeploymentScanner.java:225)
    at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.
    run(AbstractDeploymentScanner.java:202)
    Caused by: org.jboss.util.NestedSQLException: Could not create connection; - nes
    ted throwable: (java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDB
    C]Error establishing socket.); - nested throwable: (org.jboss.resource.ResourceE
    xception: Could not create connection; - nested throwable: (java.sql.SQLExceptio
    n: [Microsoft][SQLServer 2000 Driver for JDBC]Error establishing socket.))
    at org.jboss.resource.adapter.jdbc.local.LocalDataSource.getConnection(L
    ocalDataSource.java:106)
    at org.jboss.ejb.plugins.cmp.jdbc.SQLUtil.fixTableName(SQLUtil.java:38)
    ... 53 more
    Caused by: org.jboss.resource.ResourceException: Could not create connection; -
    nested throwable: (java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for
    JDBC]Error establishing socket.)
    at org.jboss.resource.adapter.jdbc.local.LocalManagedConnectionFactory.c
    reateManagedConnection(LocalManagedConnectionFactory.java:144)
    at org.jboss.resource.connectionmanager.InternalManagedConnectionPool.cr
    eateConnection(InternalManagedConnectionPool.java:259)
    at org.jboss.resource.connectionmanager.InternalManagedConnectionPool.ge
    tConnection(InternalManagedConnectionPool.java:106)
    at org.jboss.resource.connectionmanager.JBossManagedConnectionPool$BaseP
    ool.getConnection(JBossManagedConnectionPool.java:323)
    at org.jboss.resource.connectionmanager.BaseConnectionManager2.getManage
    dConnection(BaseConnectionManager2.java:467)
    at org.jboss.resource.connectionmanager.LocalTxConnectionManager.getMana
    gedConnection(LocalTxConnectionManager.java:221)
    at org.jboss.resource.connectionmanager.BaseConnectionManager2.allocateC
    onnection(BaseConnectionManager2.java:532)
    at org.jboss.resource.connectionmanager.BaseConnectionManager2$Connectio
    nManagerProxy.allocateConnection(BaseConnectionManager2.java:814)
    at org.jboss.resource.adapter.jdbc.local.LocalDataSource.getConnection(L
    ocalDataSource.java:102)
    ... 54 more
    Caused by: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Err
    or establishing socket.
    at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source
    at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)
    at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)
    at com.microsoft.jdbc.sqlserver.tds.TDSConnection.<init>(Unknown Source)
    at com.microsoft.jdbc.sqlserver.SQLServerImplConnection.open(Unknown Sou
    rce)
    at com.microsoft.jdbc.base.BaseConnection.getNewImplConnection(Unknown S
    ource)
    at com.microsoft.jdbc.base.BaseConnection.open(Unknown Source)
    at com.microsoft.jdbc.base.BaseDriver.connect(Unknown Source)
    at java.sql.DriverManager.getConnection(DriverManager.java:512)
    at java.sql.DriverManager.getConnection(DriverManager.java:140)
    at org.jboss.resource.adapter.jdbc.local.LocalManagedConnectionFactory.c
    reateManagedConnection(LocalManagedConnectionFactory.java:133)
    ... 62 more
    17:18:17,703 INFO [EjbModule] Started
    17:18:17,703 INFO [MainDeployer] Deployed package: file:/C:/Program Files/jboss
    /jboss-3.0.4_tomcat-4.1.12/server/default/deploy/titan.jar
    17:18:17,718 ERROR [URLDeploymentScanner] MBeanException: Exception in MBean ope
    ration 'checkIncompleteDeployments()'
    Cause: Incomplete Deployment listing:
    Packages waiting for a deployer:
    <none>
    Incompletely deployed packages:
    [org.jboss.deployment.DeploymentInfo@4a95206b { url=file:/C:/Program Files/jboss
    /jboss-3.0.4_tomcat-4.1.12/server/default/deploy/titandb-service.xml }
    deployer: org.jboss.deployment.SARDeployer@e0b6f5
    status: Deployment FAILED reason: Trying to install an already registered mbea
    n: jboss.jca:service=LocalTxCM,name=MSSQLDS
    state: FAILED
    watch: file:/C:/Program Files/jboss/jboss-3.0.4_tomcat-4.1.12/server/default/d
    eploy/titandb-service.xml
    lastDeployed: 1043878650593
    lastModified: 1043878650562
    mbeans:
    ]MBeans waiting for classes:
    <none>
    MBeans waiting for other MBeans:
    [ObjectName: jboss.j2ee:jndiName=MSSQLDS,service=EJB
    state: FAILED
    I Depend On:
    Depends On Me: org.jboss.deployment.DeploymentException: Error while fixing tab
    le name; - nested throwable: (org.jboss.util.NestedSQLException: Could not creat
    e connection; - nested throwable: (java.sql.SQLException: [Microsoft][SQLServer
    2000 Driver for JDBC]Error establishing socket.); - nested throwable: (org.jboss
    .resource.ResourceException: Could not create connection; - nested throwable: (j
    ava.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Error establish
    ing socket.)))]
    can anyone please help me.
    I tried changing all the xml files, but to no success.
    Thanks in advance.

    Try to use the ping command and see if you are able to connect to the Server. This exception is usually occurs when the URL, Username or the Password is incorrect.
    Hope this helps.

  • Err : "Access Not Allowed to oracle.jdbc.driver.OraclePreparedStatement"

    Hi,
    How to resolve the error "Access Not Allowed to oracle.jdbc.driver.OraclePreparedStatement"
    in jdeveloper?
    Or
    Can you please give me some sample pgms which uses oracle.jdbc.driver.OraclePreparedStatement?
    Thanks in advance,
    Senthil Kumar M.

    This is the error from the trace logs...
    application [XMII] Cannot send an HTTP error response [500 Application error occurred during request processing. (details: com.sap.xmii.Illuminator.logging.LHException: com.sap.xmii.Illuminator.logging.LHException: java.lang.NoClassDefFoundError: oracle.jdbc.driver.OraclePreparedStatement)].
    The error is: com.sap.engine.services.servlets_jsp.server.exceptions.WebIOException: The stream is closed.
    Exception id: [0050569D6ACD006A0000010C000023D300046F4B653C90D7]
    I could not find anything on the SDN regarding this message, so I may need to open up an OSS note.
    Thanks
    Skip Ford

  • Problem with JDBC and Tomcat

    I don't know where the problem originate, the only thing in my memory is that the program worked very well on my PC yesterday, but today, without even slightest change, it doesn't work anymore. As to debug it, I simplified the codes to the least, but it still refuse to work. I was beaten down by this problem totally, and cannot make out any solution for it, so, I come here, hoping to find a warrior to kill this damned bug for me.
    My program is a Servlet, but for the purpose of debugging, I have recode it to an Application/Servlet. When run as a application, I can get the result expected, but as a Servlet, :-(, maybe you should see it by yourself. My server software is Tomcat 4.1.15, and the JDK version is 1.4.0. To excute this program, you should add Data Source "Test" to ODBC.
    ///////////////////////code begins/////////////////////////
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class Ex extends HttpServlet
         int ErrorType = 0;
         String err = new String("");
         public static void main(String args[]) throws Exception{
              Ex cEx = new Ex();
              cEx.init();     
              System.out.println(cEx.ErrorType);     
         public void init() {
              String url = "jdbc:odbc:Test";
              ErrorType = 3;     //passed
              try{
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              } catch (ClassNotFoundException e) {
                   e.printStackTrace();
                   ErrorType = 1; //trapped in Class.forName
              try{
                   Connection c = DriverManager.getConnection(url);
              } catch (SQLException e) {
                   e.printStackTrace();
                   ErrorType = 2; //trapped in DriverManager.getConnection
                   err = e.getMessage();
         public void service(HttpServletRequest req, HttpServletResponse res)
                   throws IOException {
              res.setContentType("text/html; charset=GB2312");
              PrintWriter out = res.getWriter();
              out.println("Success " + "<p>" + ErrorType + "<p>" +err);
              out.close();
    //////////////////////////code ends///////////////////////////////
    The result from the Servlet tell me that the problem occurred within the connection process, I don't know who should be responsible to this - Tomcat or JDBC?

    If you could print the exception that you got then that would help :) In the mean time, I could make a guess. It is unlikely that your application server (in this case, Tomcat) is blocking connections from your servlet. So the problem is either with JDBC directly or with the underlying datasource. It seems unlikely that it is JDBC given that you have stated that the code has not changed and it works in application form.
    My guess would be that you are coming up against some sort of security constraint (eg: your DBMS is letting you log in from one IP but not another?, your Java plug-in security policy is disallowing the connection?). It's hard to say.
    But if it works as an application but not via a servlet then you could try putting this in your java.policy file, which is located in the directory where your plug-ins are installed (eg: "C:\Program Files\Java\<version>\lib\security\") on Windows systems;
    permission java.net.SocketPermission "bend xp:1099", "listen,connect,accept";
    Try that, see if it works :)
    Ben

  • Error when run Application with jdbc  Help me please

    this my code:
    public void resultado() {
    String ClassName = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@educacion04:1521:ora92";
    Connection con;
    Statement stmt;
    try {
    Class.forName(ClassName);
    } catch(java.lang.ClassNotFoundException e) {
    System.err.print("ClassNotFoundException: ");
    System.err.println(e.getMessage());
    try {
    con = DriverManager.getConnection(url,"ora1", "oracle");
    stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
    ResultSet.CONCUR_UPDATABLE);
    ResultSet uprs = stmt.executeQuery("SELECT * FROM ANEXO ");
    uprs.moveToInsertRow();
    uprs.updateString("cod_ane", "uno");
    uprs.updateString("cod_informe", "dos");
    uprs.updateString("", "tres");
    uprs.insertRow();
    uprs.updateString("cod_ane", "cuatro");
    uprs.updateString("cod_informe", "cinco");
    uprs.updateString("desc_anexo", "seis");
    uprs.insertRow();
    uprs.beforeFirst();
    System.out.println("Table ANEXO after insertion:");
    while (uprs.next()) {
    String name = uprs.getString("cod_ane");
    String id = uprs.getString("cod_informe");
    String price = uprs.getString("desc_anexo");
    System.out.print(name + " " + id + " " + price);
    uprs.close();
    stmt.close();
    con.close();
    con.commit();
    } catch(SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    WHEN CALL FUNCTION?????
    send this:
    ClassNotFoundException: oracle.jdbc.driver.OracleDriver
    SQLException: No suitable driver

    Are you sure Oracle driver (classes12.jar or classes12.zip) is in your classpath ???

  • Exception in thread "main" java.lang.ClassNotFoundException: oracle.jdbc.dr

    Hi
    I am trying to use type 4 driver to connect to my Oracle 9i Rel2 database. I downloaded the odbc14.jar from oracle and added in the C:\Oracle9i\jdbc\lib path. As on the website, I setup my environment:
    Setting Up Your Environment
    On Win95/Win98/NT:
    - Add [ORACLE_HOME]\jdbc\lib\classes111.zip and
    [ORACLE_HOME]\jdbc\lib\nls_charset11.zip to your CLASSPATH.
    (Add classes12.zip and nls_charset12.zip if JDK 1.2.x or 1.3 is
    used. Add ojdbc14.jar and nls_charset12.zip if JDK 1.4 is used.)
    - Make sure [ORACLE_HOME]\bin is in your PATH.
    Still I am getting the following error during runtime:
    Exception in thread "main" java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at jdbc.InsertQueryEx.main(InsertQueryEx.java:11)
    Below is the source code:
    import java.sql.*;
    import java.io.*;
    public class InsertQueryEx {
    public static void main(String[] args)throws Exception{
    Class.forName("oracle.jdbc.OracleDriver");
    Connection con = DriverManager.getConnection("jdbc:oracle:thin:@Prashy:1521:orcl", "scott", "tiger");
    DataInputStream din = new DataInputStream(System.in);
    Statement stmt = con.createStatement();
    while(true){
    try{
    System.out.println("enter emp name");
    String name = din.readLine();
    System.out.println("enter emp no");
    int no = Integer.parseInt(din.readLine());
    System.out.println("enter emp salary");
    float sal = Float.parseFloat(din.readLine());
    System.out.println("enter emp address");
    String addr = din.readLine();
    int count = stmt.executeUpdate("insert into myemp values("+no+",'"+name+"',"+sal+",'"+addr+"')");
    if(count>0)
    System.out.println("Record added");
    else
    System.out.println("Failed");
    catch (Exception e){
    System.err.println("Exception: "+e.getMessage());
    Any help is appreciated
    Thanks
    Prashant

    I am sorry but I did add those in the classpath but still getting this error:
    This is what I have for user variable in classpath:
    .;C:\Oracle9i\jdbc\lib\ojdbc14.jar;C:\Oracle9i\jdbc\lib\nls_charset12.jar
    error is:
    java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver
         at java.net.URLClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClassInternal(Unknown Source)
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Unknown Source)
         at jdbc.InsertQueryEx.main(InsertQueryEx.java:14)
    Thanks

  • Need help w corba/jdbc class

    hi
    i'm trying to get this class to work right, i don't think i'm coding it the right way, especially the getAllAccounts() and selectAccounts() methods. this code compiles cleanly, but i get runtime exceptions when i try to run my app. my runtime exceptions look like
    ############################ StackTrace ############################
    java.lang.NullPointerException
    at com.kafein.accountServices.AccountServiceImpl.getAllAccounts(AccountS
    erviceImpl.java:218)
    at com.kafein.idl.accountServices.AccountServicePOA._invoke(AccountServi
    cePOA.java:74)
    at org.jacorb.poa.RequestProcessor.invokeOperation(RequestProcessor.java
    :247)
    at org.jacorb.poa.RequestProcessor.process(RequestProcessor.java:477)
    at org.jacorb.poa.RequestProcessor.run(RequestProcessor.java:604)
    and
    Creating 100 Accounts
    org.omg.CORBA.UNKNOWN: This exception was reported by the server, it is only re-
    thrown here. vmcid: 0x0 minor code: 0 completed: No
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Sou
    rce)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.jacorb.orb.SystemExceptionHelper.read(SystemExceptionHelper.java:
    157)
    at org.jacorb.orb.connection.ReplyInputStream.checkExceptions(ReplyInput
    Stream.java:117)
    at org.jacorb.orb.Delegate.invoke(Delegate.java:942)
    at org.omg.CORBA.portable.ObjectImpl._invoke(Unknown Source)
    at com.kafein.idl.accountServices._AccountServiceStub.getAllAccounts(_Ac
    countServiceStub.java:134)
    at com.kafein.client.AccountClient.main(AccountClient.java:111)
    org.omg.CORBA.UNKNOWN: This exception was reported by the server, it is only re-
    thrown here. vmcid: 0x0 minor code: 0 completed: No
    ORB shutting down...
    code for this class is below...
    // AccountServiceImpl.java: The AccountService Implementation
    package com.kafein.accountServices;
    import java.util.Hashtable;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import junit.framework.TestCase;
    import junit.framework.Test;
    import junit.framework.TestSuite;
    import org.omg.PortableServer.*;
    import com.kafein.idl.accountServices.AccountServicePOA;
    import com.kafein.idl.accountServices.AccountEntryStruct;
    import com.kafein.idl.accountServices.AccountStruct;
    import com.kafein.idl.utilities.DateTimeStruct;
    import com.kafein.idl.exceptions.NotFoundException;
    import com.kafein.idl.exceptions.DataValidationException;
    import com.kafein.idl.errorCodes.DataValidationErrorCodes;
    import com.kafein.utils.ServiceHandler;
    import com.kafein.utils.Log;
    import java.net.URL;
    import java.sql.*;
    import java.util.*;
    * AccountServiceImpl is an implementation of the
    * idl.accountServices.AccountService interface.
    public class AccountServiceImpl extends AccountServicePOA {
      POA poa;
      private Hashtable accounts = new Hashtable(); // collection of Accounts
      private static int nextAccountID = 1; // global account ID
      Connection connection;
      Vector connections;
      Statement statement;
      PreparedStatement preparedStatement;
       * Construct an instance.
      public AccountServiceImpl(POA aPOA, String driver, String url, String user, String password) {
        super();
        poa = aPOA;
        driver = driver;
        url = url;
        user = user;
        password = password;
        connections = new Vector();
        // Connect to Database
        try {
            connect(driver,url,user,password);
        catch(Exception e) {
               e.printStackTrace();       
        // Simple Database Select
        try {
            testSimpleSelect();
        catch(Exception e) {
               e.printStackTrace();       
        // Database Select
        try {
            testSelect();
        catch(Exception e) {
               e.printStackTrace();       
       * Overloaded constructor for unit tests.
      protected AccountServiceImpl() {
        poa = null;
       * createAccount is used by administrator to add a new Account
       * in the system.
       * @param newAccount AccountEntryStruct containing data for new account
       * @return int the new unique Account ID
       * @exception com.kafein.idl.exceptions.DataValidationException
      public int createAccount(AccountEntryStruct newAccount) throws
        DataValidationException {
        validateData (newAccount); // throws DataValidationException;
        int accountID = getNextID();     
        // Create new Account.
        Account anAccount = new Account(accountID,
                            newAccount.userName,
                            newAccount.userEmail,
                            newAccount.creditCardType,
                            newAccount.creditCardNumber,
                            newAccount.creditCardExpirationDate.year,
                            newAccount.creditCardExpirationDate.month,
                            newAccount.userPassword,
                            newAccount.initialBalance);
    // Insert here / call method insertAccount() pass it in an account object
    // or call manager object - accountmanager.put()
        // Insert Account into Database
        try {
            insertAccount(anAccount);
        catch(Exception e) {
               e.printStackTrace();       
        accounts.put(accountID,anAccount);
        return accountID;
       * isAccountValid is used to validate a user logon.
       * @param accountID AccountID
       * @param userPassword String
       * @return boolean true to indicate an existing Account
      public boolean isValidAccount (int accountID, String userPassword) {
        // Get account with key equal to accountID.
        AccountStruct anAccount;
        try {
          anAccount = (AccountStruct) getAccount (accountID);
        catch (NotFoundException e) {
          return false;
        // Verify password.
        return (anAccount.userPassword.equals(userPassword) ? true : false);
       * getAccount is used to retrieve an existing Account in the system
       * @param int AccountID
       * @return AccountStruct containing data for the existing Account
       * @exception com.kafein.idl.exceptions.NotFoundException
      public AccountStruct getAccount(int accountID)throws
        NotFoundException {
        // Verify that accountID is within an appropriate interval.
        if (accountID < 1 || accountID > accounts.size()) {
          throw new NotFoundException(DataValidationErrorCodes.INVALID_ACCOUNT_ID,
                          "Account ID not found");
        // Get Account and convert to AccountStruct (which is returned).
        Account anAccount = (Account) accounts.get(accountID);
        return anAccount.getAccountStruct();
       * getAllAccounts is used to retrieve all existing Accounts in the system
       * @return AccountStruct[] containing all existing Accounts.
       * @fyi returns an empty sequence if no Accounts exist
      // GetAllAcounts method v. 2 - rather than enumerating through the vector
      // call a method that returns a collection of objs in that method where
      // you do select stmts
      public AccountStruct[] getAllAccounts() {
        // Allocate the array of AccountStructs.
        Vector results = new Vector();
        try {
                results = selectAccounts();
        catch(Exception e) {
               e.printStackTrace();       
        //Vector results = selectAccounts();
        int lastKey = results.size();
        //int lastKey = accounts.size();
        AccountStruct[] accountSequence = new AccountStruct[lastKey];
        if (lastKey==0) {
          return accountSequence;
        // Create AccountStructs from Accounts.
        for (int i = 1; i <= lastKey; i++) {
          Account anAccount = (Account) accounts.get(i);
          accountSequence[i-1] = anAccount.getAccountStruct();
        return accountSequence;
       * validateData is used to check new account data.
       * @param newAccount AccountEntryStruct containing data for new account
       * @exception com.kafein.idl.exceptions.DataValidationException
      protected void validateData(AccountEntryStruct newAccount) throws
        DataValidationException {
        // Check all of the member data in newAccount.
        if (newAccount.userName.equals("")) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_USER_NAME,
              "User Name must not be empty");
        if (newAccount.userEmail.equals("")) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_USER_EMAIL,
              "User Email must not be empty");
        if (newAccount.creditCardType.equals("")) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_CREDIT_CARD_TYPE,
              "Credit card type must not be empty");
        if (newAccount.creditCardNumber.equals("")) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_CREDIT_CARD_NUMBER,
              "Credit card number must not be empty");
        // Compare creditCardExpirationDate to current date
        // (we only consider year and month).
        GregorianCalendar now = new GregorianCalendar();
        DateTimeStruct proposed = newAccount.creditCardExpirationDate;
        if (proposed.year < now.get (Calendar.YEAR) ||
         (proposed.year == now.get (Calendar.YEAR) &&
          proposed.month < now.get (Calendar.MONTH) + 1)) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_CREDIT_CARD_EXPIRATION_DATE,
              "Credit card has expired");
        if (newAccount.userPassword.equals("")) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_USER_PASSWORD,
              "Password must not be empty");
        else if (!newAccount.userPassword.equals(newAccount.userPasswordVerification)) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_USER_PASSWORD,
              "Password verification failure");
        if (newAccount.initialBalance < 0.0F) {
          throw new DataValidationException(
              DataValidationErrorCodes.INVALID_BALANCE,
              "Account Balance cannot have a negative balance");
       * getNextID is used to generate a unique ID.
       * Needs a much better implementation that generates a globally unique ID!
       * @return int an Account ID
      protected synchronized int getNextID() {
        nextAccountID++;
        return nextAccountID - 1;
       * override _default_POA to return this servant's POA, not Root POA
      public POA _default_POA() {
        return poa;
       * jdbc related methods
      public void connect(String driver, String url, String user, String password)
                    throws Exception {
            try {
                // Load JDBC driver
                Class.forName(driver);
                System.out.println("Connecting to " + url);
                connection = DriverManager.getConnection(url, user, password);
                connections.add(connection);
                connection.setAutoCommit(false);
            } catch(Exception e) {
                System.err.println("System Exception in connect");
                System.err.println(e);
                throw e;
      public void closeConnection() throws Exception {
            try {
                Enumeration myEnum = connections.elements();
                while ( myEnum.hasMoreElements() ) {
                    System.out.println("Closing connection");
                    ((Connection) myEnum.nextElement()).close();
            } catch (Exception e) {
                System.err.println("System Exception in closeConnection");
                System.err.println(e);
                throw e;
      private void testSimpleSelect() throws Exception {
            try {
                Statement statement = connection.createStatement();
                ResultSet rs = statement.executeQuery("Select 1 from ACCOUNT");
                if (rs != null && rs.next()) {
                   int value = rs.getInt(1);
                   System.out.println("Fetched value " + value);
                connection.commit();
                statement.close();
            } catch(Exception e) {
                System.err.println("System Exception in testSimpleSelect");
                System.err.println(e);
                throw e;
      private void testSelect() throws Exception {
            try {
                Statement statement = connection.createStatement();
                ResultSet rs = statement.executeQuery(
                    "Select ACCT_ID, ACCT_USERNAME, ACCT_USEREMAIL, ACCT_CC_TYPE, ACCT_CC_NUMBER, ACCT_CC_EXPYR, ACCT_CC_EXPMO, ACCT_USERPASSWORD, ACCT_USERBALANCE from ACCOUNT LIMIT 1");
                System.out.println("Account ID   User Name     User Email     CC Type     CC Number     CC Expyr CC Expmo User Password     User Balance");
                while (rs != null && rs.next()) {
                    int acct_id = rs.getInt(1);
                    String acct_username = rs.getString(2);
                    String acct_useremail = rs.getString(3);
                    String acct_cc_type = rs.getString(4);
                    String acct_cc_number = rs.getString(5);
                    int acct_cc_expyr = rs.getInt(6);
                    int acct_cc_expmo = rs.getInt(7);
                    String acct_userpassword = rs.getString(8);
                    float acct_userbalance = rs.getFloat(9);
                    System.out.println(acct_id + "         " +
                                       acct_username + "   " +
                                       acct_useremail + "   " +
                                       acct_cc_type + "   " +
                                       acct_cc_number + "   " +
                                       acct_cc_expyr + "   " +
                                       acct_cc_expmo + "   " +
                                       acct_userpassword + "   " +
                                       acct_userbalance);
                connection.commit();
                statement.close();
            } catch(Exception e) {
                System.err.println("System Exception in testSelect");
                System.err.println(e);
                throw e;
      private void testLoadData() throws Exception {
            int numberOfAccounts = 5;
            String  acct_username    = "<--20 BYTE STRING-->";
            String  acct_useremail = "<--20 BYTE STRING-->";
         String  acct_cc_type = "TEST ";
            String  acct_cc_number = "<--20 BYTE STRING-->";
            int  acct_cc_expyr = 2000;
            int  acct_cc_expmo = 1;
            String  acct_userpassword = "<--20 BYTE STRING-->";
            float     acct_userbalance = 0.0F;
            int     acct_id = 0;
         try {
                System.out.println("Inserting data...");
                connection.setAutoCommit(false);
                // Calculate Start time
                System.out.println("Starting data insertion (" + numberOfAccounts +
                    " rows) into ACCOUNT table..");
                long startTime = System.currentTimeMillis();
                preparedStatement = connection.prepareStatement(
                    "INSERT INTO ACCOUNT (ACCT_ID, ACCT_USERNAME, ACCT_USEREMAIL, ACCT_CC_TYPE, ACCT_CC_NUMBER, " +
                    "ACCT_CC_EXPYR, ACCT_CC_EXPMO, ACCT_USERPASSWORD, ACCT_USERBALANCE) VALUES ( ?, ?, ?, ?, ?, ? , ?, ?, ?)");
                // Insert accounts in ACCOUNT table
                for (int i = 1; i <= numberOfAccounts; i++) {
                    acct_id  = i * 1000;
                    preparedStatement.setInt(1, acct_id);
                    preparedStatement.setString(2, acct_username);
                    preparedStatement.setString(3, acct_useremail);
                    preparedStatement.setString(4, acct_cc_type);
                    preparedStatement.setString(5, acct_cc_number);
                    preparedStatement.setInt(6, acct_cc_expyr);
                    preparedStatement.setInt(7, acct_cc_expmo);
                    preparedStatement.setString(8, acct_userpassword);
                    preparedStatement.setFloat(9, acct_userbalance);
              preparedStatement.executeUpdate();
                    connection.commit();
                System.out.println(numberOfAccounts + " accounts created.");
                preparedStatement.close();
                long stopTime = System.currentTimeMillis();
                System.out.println("Account table load complete.");
                System.out.println("Load time = " +
                                   ((stopTime - startTime)/(1000f)) + " seconds");
                System.out.println("Data insertion complete");
            } catch(Exception e) {
                System.err.println("System Exception in loadData");
                System.err.println(e);
                throw e;
       * insertAccount is used to insert a new Account in the Database
       * @param int AccountID
       * @return AccountStruct containing data for the existing Account
      private void insertAccount(Account anAccount) throws Exception {
              AccountStruct anAccountStruct = anAccount.getAccountStruct();  
         int numberOfAccounts = 1;
         String  acct_username    = anAccountStruct.userName;
            String  acct_useremail = anAccountStruct.userEmail;
         String  acct_cc_type = anAccountStruct.creditCardType;
            String  acct_cc_number = anAccountStruct.creditCardNumber;
         int acct_cc_expyr = anAccountStruct.creditCardExpirationDate.year;
            int acct_cc_expmo = anAccountStruct.creditCardExpirationDate.month;
            String  acct_userpassword = anAccountStruct.userPassword;
            float     acct_userbalance = anAccountStruct.accountBalance;
            int     acct_id = anAccountStruct.accountID;
         try {
                System.out.println("Inserting data...");
                connection.setAutoCommit(false);
    //instead of system.out just log
                // Calculate Start time
                System.out.println("Starting data insertion ( 1" +
                    " row) into ACCOUNT table..");
                long startTime = System.currentTimeMillis();
                preparedStatement = connection.prepareStatement(
                    "INSERT INTO ACCOUNT (ACCT_ID, ACCT_USERNAME, ACCT_USEREMAIL, ACCT_CC_TYPE, ACCT_CC_NUMBER, " +
                    "ACCT_CC_EXPYR, ACCT_CC_EXPMO, ACCT_USERPASSWORD, ACCT_USERBALANCE) VALUES ( ?, ?, ?, ?, ?, ? , ?, ?, ?)");
                    acct_id  = 1000;
                    preparedStatement.setInt(1, acct_id);
                    preparedStatement.setString(2, acct_username);
                    preparedStatement.setString(3, acct_useremail);
                    preparedStatement.setString(4, acct_cc_type);
                    preparedStatement.setString(5, acct_cc_number);
                    preparedStatement.setInt(6, acct_cc_expyr);
                    preparedStatement.setInt(7, acct_cc_expmo);
                    preparedStatement.setString(8, acct_userpassword);
                    preparedStatement.setFloat(9, acct_userbalance);
              preparedStatement.executeUpdate();
                    connection.commit();
                System.out.println("1 account created.");
                preparedStatement.close();
                long stopTime = System.currentTimeMillis();
                System.out.println("Account table load complete.");
                System.out.println("Load time = " +
                                   ((stopTime - startTime)/(1000f)) + " seconds");
                System.out.println("Data insertion complete");
            } catch(Exception e) {
                System.err.println("System Exception in loadData");
                System.err.println(e);
                throw e;
      private Vector selectAccounts() throws Exception {
            try {
                // Create Vector to hold individual Account values
             Vector mainvector = new Vector();
             Vector values = new Vector();
             Statement statement = connection.createStatement();
                ResultSet rs = statement.executeQuery(
                    "Select ACCT_ID, ACCT_USERNAME, ACCT_USEREMAIL, ACCT_CC_TYPE, ACCT_CC_NUMBER, ACCT_CC_EXPYR, ACCT_CC_EXPMO, ACCT_USERPASSWORD, ACCT_USERBALANCE from ACCOUNT");
                System.out.println("Account ID   User Name     User Email     CC Type     CC Number     CC Expyr CC Expmo User Password     User Balance");
             // Iterate through result set
             while (rs != null && rs.next()) {
              // Make sure values is empty
              values.clear();
              int acct_id = rs.getInt(1);
                    String acct_username = rs.getString(2);
                    String acct_useremail = rs.getString(3);
                    String acct_cc_type = rs.getString(4);
                    String acct_cc_number = rs.getString(5);
                    int acct_cc_expyr = rs.getInt(6);
                    int acct_cc_expmo = rs.getInt(7);
                    String acct_userpassword = rs.getString(8);
                    float acct_userbalance = rs.getFloat(9);
              // Populate Vector values
              values.addElement(rs.getObject(1));
              values.addElement(rs.getObject(2));
              values.addElement(rs.getObject(3));
              values.addElement(rs.getObject(4));
              values.addElement(rs.getObject(5));
              values.addElement(rs.getObject(6));
              values.addElement(rs.getObject(7));
              values.addElement(rs.getObject(8));
              values.addElement(rs.getObject(9));
              mainvector.addElement(values);
                    System.out.println(acct_id + "         " +
                                       acct_username + "   " +
                                       acct_useremail + "   " +
                                       acct_cc_type + "   " +
                                       acct_cc_number + "   " +
                                       acct_cc_expyr + "   " +
                                       acct_cc_expmo + "   " +
                                       acct_userpassword + "   " +
                                       acct_userbalance);
                connection.commit();
                statement.close();
             return mainvector;
            } catch(Exception e) {
                System.err.println("System Exception in selectAccounts");
                System.err.println(e);
                throw e;
        }

    line 217 and 218 is
    Account anAccount = (Account) accounts.get(i);
    accountSequence[i-1] = anAccount.getAccountStruct();
    i realized that
    Account anAccount = (Account) accounts.get(i);
    was a typo. what it should have been was
    Account anAccount = (Account) results.get(i);
    so my getAllAccounts() method now looks like
       * getAllAccounts is used to retrieve all existing Accounts in the system
       * @return AccountStruct[] containing all existing Accounts.
       * @fyi returns an empty sequence if no Accounts exist
      // GetAllAcounts method v. 2 - rather than enumerating through the vector
      // call a method that returns a collection of objs in that method where
      // you do select stmts
      public AccountStruct[] getAllAccounts() {
        // Allocate the array of AccountStructs.
        Vector results = new Vector();
        try {
                results = selectAccounts();
        catch(Exception e) {
               e.printStackTrace();       
        //Vector results = selectAccounts();
        int lastKey = results.size();
        //int lastKey = accounts.size();
        AccountStruct[] accountSequence = new AccountStruct[lastKey];
        if (lastKey==0) {
          return accountSequence;
        // Create AccountStructs from Accounts.
        for (int i = 1; i <= lastKey; i++) {
          Account anAccount = (Account) results.get(i);
          accountSequence[i-1] = anAccount.however, i still get the same runtime errors.
    is my selectAccounts() method returning a null?

  • Getting error while Creating a JDBC connection from Java Class

    Hi,
    I am getting the exception pasted below:
    Exception in thread "main" java.lang.AbstractMethodError
    at JvMakeVTable(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at JvPrepareClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at JvWaitForState(java.lang.Class, int) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.VMClassLoader.linkClass0(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.VMClassLoader.resolveClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.initializeClass() (/usr/lib/libgcj.so.5.0.0)
    at oracle.jdbc.driver.OracleStatement.executeQuery(java.lang.String) (Unknown Source)
    at oracle.jdbc.dbaccess.DBAccess.setNlsParamsClient(oracle.jdbc.driver.OracleConnection) (Unknown Source)
    at oracle.jdbc.ttc7.TTC7Protocol.initNls(oracle.jdbc.driver.OracleConnection) (Unknown Source)
    at oracle.jdbc.driver.OracleConnection.OracleConnection(oracle.jdbc.dbaccess.DBAccess, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.Properties) (Unknown Source)
    at oracle.jdbc.driver.OracleDriver.getConnectionInstance(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.Properties) (Unknown Source)
    at oracle.jdbc.driver.OracleDriver.connect(java.lang.String, java.util.Properties) (Unknown Source)
    at java.sql.DriverManager.getConnection(java.lang.String, java.util.Properties) (/usr/lib/libgcj.so.5.0.0)
    at java.sql.DriverManager.getConnection(java.lang.String, java.lang.String, java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    The code raising this error is :
    try
                   Class.forName("oracle.jdbc.driver.OracleDriver");
              catch (Exception Exp)
                   System.out.println("Error while getting the class : "+Exp);
    try
                   String url = "jdbc:oracle:thin:@hostname:port:SID";
                   String user = "apps";
                   String password = "password";
                   con = DriverManager.getConnection(url,user,password);
    catch (Exception ex)
                   System.err.println("SQLException: " + ex.getMessage());
    Any help in this is appreciated.
    Regards
    Jujaar

    Why do you have the Class.forName() in a separate try-catch block than the DriverManager.getConnection()?
    Try placing everything in the same try-catch block to see if that resolves your problem.
    You may also want to try using an OracleDataSource.
    OracleDataSource ods = new OracleDataSource();
    String url = "jdbc:oracle:thin:@//hostname:port/SID",
    ods.setURL(url);
    ods.setUser("apps");
    ods.setPassword("password");
    Connection conn = ods.getConnection();
    Refer to http://st-doc.us.oracle.com/11/111/java.111/b31224/getsta.htm#i1008334 for details on how to connect to the database using a Data Source.

  • HELP! Jdbc connection to oracle ClassNotFoundException classpath issues..

    Okay I am a newbie to this but all the other posts concerning this just say add the classes12.jar to my classpath.
    I am using websphere 5.0
    connecting to a 9i db.
    after trying to find out what my classpath is ( websphere 5.0 makes it difficult to see it) i found this:
    <?xml version="1.0" encoding="UTF-8"?>
    <classpath>
    <classpathentry kind="var"
    path="SERVERJDK_50_PLUGINDIR/jre/lib/rt.jar"
    rootpath="SERVERJDK_SRCROOT" sourcepath="SERVERJDK_50_PLUGINDIR/src.jar"/>
    <classpathentry kind="src" path="Java Source"/>
    <classpathentry kind="var" path="WAS_50_PLUGINDIR/lib/j2ee.jar"/>
    <classpathentry kind="var" path="WAS_50_PLUGINDIR/lib/servletevent.jar"/>
    <classpathentry kind="var" path="WAS_50_PLUGINDIR/lib/ivjejb35.jar"/>
    <classpathentry kind="var" path="WAS_50_PLUGINDIR/lib/runtime.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/string.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/jaxen-full.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/utility.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/jspsql.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/xercesImpl.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/xalan.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/datetime.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/mailer.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/dom.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/jstl.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/standard.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/jdbc2_0-stdext.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/saxpath.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/sax.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/dbbeans.jar"/>
    <classpathentry kind="lib" path="Web Content/WEB-INF/lib/jaxp-api.jar"/>
    <classpathentry kind="lib" path="C:/oracle/ora92/jdbc/lib/classes12.jar"/>
    <classpathentry kind="output" path="Web Content\WEB-INF\classes"/>
    </classpath>
    to me it looks like it is in my classpath.. (if thats what this is).
    I have imported the classes12.jar file several times through out my project to no avail.
    the error i get it here:
    Error: It Screwed up agian java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
    SystemOut O Connecting ... cisinv
    Error: java.sql.SQLException: No suitable driver
    SystemErr R Exception: null
    from this code:
    package Business;
    import java.sql.Connection;
    import java.sql.Driver;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    * @author jeffreak
    * To change this generated comment edit the template variable "typecomment":
    * Window>Preferences>Java>Templates.
    * To enable and disable the creation of type comments go to
    * Window>Preferences>Java>Code Generation.
    public class beanDbConnect {
         * Constructor for beanDbConnect.
         public beanDbConnect() {
              super();
         private Connection con = null;
         private Statement cmd = null;
         private ResultSet rs = null;
         public Connection connect()
              //Declare variable
              boolean blnSuccessfulOpen = false;
              Driver driver;
              String driverName;
              String serverAddress;
              //Begin try block
              try
                   //Load JdbcOdbcDriver
                   driverName = "oracle.jdbc.driver.OracleDriver";
                                  //oracle.jdbc.driver.OracleDriver     
                   System.out.println("Loading ..." + driverName);
                   //try{
                   Class.forName(driverName).newInstance();
                   //catch (Exception err)
    //                    System.err.println("Error: new instance: " + err.toString());
              System.out.println("Database loaded successfully");
              //catch (ClassNotFoundException e)
              catch (Exception e)
                   System.err.println("Error: It Screwed up agian " + e.toString());
                   blnSuccessfulOpen = false;
              try
                   //Instantiate connection to bean-defined DSN
                   //serverAddress = ("jdbc:oracle:thin:scott/tiger@localhost:1243:" + dbInstance);
                   System.out.println("Connecting ... " );
                   String serverName = "**********";//changed for post
                   String portNumber = "1521";
                   String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + "cisinv";
                   con = DriverManager.getConnection(url, "scott", "tiger");
                   System.out.println("Ready.");
                   blnSuccessfulOpen = true;
              catch (SQLException e)
                   System.err.println("Error: " + e.toString());
              //End try block
              return con;
         }//end connect()
    Please help. ive been working on it for days =(.

    If you're running a Web app, put all JARs that your app needs in the WEB-INF/lib directory. That's always in the CLASSPATH.
    I don't know WebSphere. Do you really have to edit something to add all those CLASSPATH entries?
    In Tomcat, all I'd have to do is put a WAR file in the webapps directory.
    Your code needs some work. You're not following Sun's Java coding standards. Capitalize your class name, for starters.
    Is the username and password for your database still "scott" and "tiger"? Nice security there.
    Your connect method makes a database connection. Do you leave it to users to close it? (You do close your connections when you're done with them, don't you?)
    I'd make Connection a data member and create it in a constructor. I'd write a close method to close it up.
    Doesn't WebSphere do connection pooling? Do you really want to write your own class to handle this?
    MOD

  • Help  connection to oracle db using jdbc

    Hi
    I am trying to connect to a oracle database. I am using Oracle 9 and jsdk 1.4.2. but i keep getting the following error and i dont know what iam doing wrong.
    I have put in my classpath where the orcle drivers are. I have also tried puting the drivers in j2sdk/jre/lib folder (files copied nls_charset12.zip,classes12.zip,ojdbc14.jar). My code compiles and runs but the error i get is
    "java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver"
    SAMPLE of my code:
    Class.forName("oracle.jdbc.driver.OracleDriver");
    String dataSource = "jdbc:oracle:thin:@devflgdb";
    Connection con = DriverManager.getConnection(dataSource,"babu_s2","babu_s2");

    I am working on the same; here is my servlet code, hope it helps
    private static void loadJDBCDriver ()
    System.out.println ("Loading Database driver...");
    try {
         DriverManager.registerDriver ( new oracle.jdbc.driver.OracleDriver());
    catch (Exception e) {}
    try {
    DriverManager.registerDriver ( new sun.jdbc.odbc.JdbcOdbcDriver() );
    catch (Exception e2) {
    System.err.println ("loadJDBCDriver: " + e2.toString());
    return;
    System.out.println ("Database driver loaded...");
    private static Connection getConnected () {
    System.out.println ("Establishing database connection...");
    String jdbc_url;
    Connection conn;
    try {
    jdbc_url = "jdbc:oracle:thin:@localhost:1521:oracle";
    conn = DriverManager.getConnection (jdbc_url, "scott", "tiger");
    catch (Exception e) {
    try {
    jdbc_url = "jdbc:odbc:BookNook";
    conn = DriverManager.getConnection (jdbc_url);
    catch (SQLException e2) {
    System.err.println ("getConnected: " + e2.toString() );
    return null;
    System.out.println ("Database connection established ...");
    return conn;

  • Issues while configuring java application using JDO with MS JDBC Driver 1.0

    We are in the process of configuring our java application with the production version of SQL Server 2005 Java Database Connectivity (JDBC) Driver 1.0. We are facing issues getting it to work with Sun App Server using JDO concept.
    After creating the data store, adding the JDBC driver to the application server classpath through console and also copying the driver into the lib directory, we are still getting the below error.
    Following is the stack trace encountered while running the application
    [#|2006-02-15T10:21:25.493+0530|WARNING|sun-appserver-pe8.1_02|javax.enterprise.system.container.ejb.entity.finder|_ThreadID=30;|JDO74010: Bean 'InventoryEJB' method ejbFindAllInventoryItems: problems running JDOQL query.
    com.sun.jdo.api.persistence.support.JDOFatalInternalException: JDO76519: Failed to identify vendor type for the data store.
    NestedException: java.sql.SQLException: Error in allocating a connection. Cause: javax.transaction.SystemException
         at com.sun.jdo.spi.persistence.support.sqlstore.impl.SQLPersistenceManagerFactory.initializeSQLStoreManager(SQLPersistenceManagerFactory.java:870)
         at com.sun.jdo.spi.persistence.support.sqlstore.impl.SQLPersistenceManagerFactory.getFromPool(SQLPersistenceManagerFactory.java:786)
         at com.sun.jdo.spi.persistence.support.sqlstore.impl.SQLPersistenceManagerFactory.getPersistenceManager(SQLPersistenceManagerFactory.java:673)
         at com.sun.jdo.spi.persistence.support.sqlstore.impl.PersistenceManagerFactoryImpl.getPersistenceManager(PersistenceManagerFactoryImpl.java:849)
         at com.sun.jdo.spi.persistence.support.sqlstore.impl.PersistenceManagerFactoryImpl.getPersistenceManager(PersistenceManagerFactoryImpl.java:681)
         at com.sun.j2ee.blueprints.supplier.inventory.ejb.InventoryEJB1142755294_ConcreteImpl.jdoGetPersistenceManager(InventoryEJB1142755294_ConcreteImpl.java:530)
         at com.sun.j2ee.blueprints.supplier.inventory.ejb.InventoryEJB1142755294_ConcreteImpl.ejbFindAllInventoryItems(InventoryEJB1142755294_ConcreteImpl.java:146)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at com.sun.enterprise.security.SecurityUtil.invoke(SecurityUtil.java:147)
         at com.sun.ejb.containers.EJBLocalHomeInvocationHandler.invoke(EJBLocalHomeInvocationHandler.java:185)
         at $Proxy164.findAllInventoryItems(Unknown Source)
         at com.sun.j2ee.blueprints.supplier.inventory.web.DisplayInventoryBean.getInventory(Unknown Source)
         at org.apache.jsp.displayinventory_jsp._jspService(displayinventory_jsp.java:119)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:105)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:860)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:336)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:301)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:251)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:860)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:249)
         at java.security.AccessController.doPrivileged(Native Method)
         at javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
         at org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:282)
         at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:165)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:257)
         at org.apache.catalina.core.ApplicationFilterChain.access$000(ApplicationFilterChain.java:55)
         at org.apache.catalina.core.ApplicationFilterChain$1.run(ApplicationFilterChain.java:161)
         at java.security.AccessController.doPrivileged(Native Method)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
         at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:723)
         at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:482)
         at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:417)
         at org.apache.catalina.core.ApplicationDispatcher.access$000(ApplicationDispatcher.java:80)
         at org.apache.catalina.core.ApplicationDispatcher$PrivilegedForward.run(ApplicationDispatcher.java:95)
         at java.security.AccessController.doPrivileged(Native Method)
         at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:313)
         at com.sun.j2ee.blueprints.supplier.inventory.web.RcvrRequestProcessor.doPost(Unknown Source)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:767)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:860)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:249)
         at java.security.AccessController.doPrivileged(Native Method)
         at javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
         at org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:282)
         at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:165)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:257)
         at org.apache.catalina.core.ApplicationFilterChain.access$000(ApplicationFilterChain.java:55)
         at org.apache.catalina.core.ApplicationFilterChain$1.run(ApplicationFilterChain.java:161)
         at java.security.AccessController.doPrivileged(Native Method)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:263)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:551)
         at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:225)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:173)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:551)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:551)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:132)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:551)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:933)
         at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:185)
         at com.sun.enterprise.web.connector.grizzly.ProcessorTask.process(ProcessorTask.java:653)
         at com.sun.enterprise.web.connector.grizzly.ProcessorTask.process(ProcessorTask.java:534)
         at com.sun.enterprise.web.connector.grizzly.ProcessorTask.doTask(ProcessorTask.java:403)
         at com.sun.enterprise.web.connector.grizzly.WorkerThread.run(WorkerThread.java:55)
    Can anyone help me on this issue?
    Regards,
    Bindu

    I have already tried this before and this not work too, but strange that even if I use JDBC:ODBC bridge driver, the return value for output parameters are not correct, that is, only return the value that I input but not the value after executed in the procedure....
    The code that I used with JDBC:ODBC bridge is as follow:
    public static void main(String[] args) {
    String url = "jdbc:odbc:;DRIVER=SQL Server;Persist Security Info=False;database=db;Server=sql;uid=sa;pwd=pwd";
              Connection con;
              ResultSet rs = null;
    CallableStatement callS = null;
              try {
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              } catch(java.lang.ClassNotFoundException e) {
                   System.err.print("ClassNotFoundException: ");
                   System.err.println(e.getMessage());
              try {
                   con=DriverManager.getConnection(url);
    callS = con.prepareCall("{ call dbo.CpJavaTest (?)}");
    callS.registerOutParameter(1, Types.INTEGER);
    callS.execute();
    rs=callS.getResultSet();
    int ret = callS.getInt(1);
    System.out.println("return value : " + ret);
                   while (rs.next()) {
                        String f1 = rs.getString(4);
                        String f2 = rs.getString(5);
                        System.out.println(f1 + " " + f2);
              } catch(SQLException ex) {
                   System.out.println("SQLException: " + ex.getMessage());
    The value of the output parameter is same as what I inputed! Hope any one can teach me how to correct it...
    Thank you very much!

  • Getting Connected for the First Time with JDBC

    Hello everyone. I am trying to make my first database connection to a mysql database with Java. I am using jdk 1.5.0, MySQL 4.1.11 nt, and I think I have the freshly downloaded driver C:\jdk1.5.0\jre\lib\ext\mysql-connector-java-3.0.16-ga-bin.jar" installed in the right spot. When I try to run the following code...
    package dbfinder;
    import java.sql.*;
    import javax.sql.*;
    import com.sun.rowset.JdbcRowSetImpl;
    import javax.sql.rowset.JdbcRowSet;
    import java.sql.ResultSetMetaData;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2005</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class DatabaseConnector {
    public DatabaseConnector() {
    public static void main(String args[]){
    Connection connection;
    Statement statement;
    // ResultSet resultSet;
    // ResultSetMetaData metaData;
    String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
    String DATABASE_URL = "jdbc:mysql://localhost/state_crime";
    String USER = "cis695d";
    String PASSWORD = "cis695d";
    JdbcRowSet rowSet = new JdbcRowSetImpl();
    try {
    Class.forName(DATABASE_DRIVER); // load database driver
    System.out.println("class loaded");
    rowSet.setUrl("DATABASE_URL");
    rowSet.setUsername(USER);
    rowSet.setPassword(PASSWORD);
    rowSet.setCommand("Select * FROM state_crime_rates");
    rowSet.execute();
    ResultSetMetaData metaData = rowSet.getMetaData();
    int numberOfColumns;
    numberOfColumns = metaData.getColumnCount();
    System.out.println(numberOfColumns);
    } catch(SQLException sqlException){
    sqlException.printStackTrace();
    System.exit(1);
    catch(ClassNotFoundException classNotFound){
    classNotFound.printStackTrace();
    System.exit(1);
    I get the following exception...
    java.sql.SQLException: No suitable driver
         at java.sql.DriverManager.getConnection(DriverManager.java:545)
         at java.sql.DriverManager.getConnection(DriverManager.java:171)
         at com.sun.rowset.JdbcRowSetImpl.connect(JdbcRowSetImpl.java:618)
         at com.sun.rowset.JdbcRowSetImpl.prepare(JdbcRowSetImpl.java:630)
         at com.sun.rowset.JdbcRowSetImpl.execute(JdbcRowSetImpl.java:526)
         at dbfinder.DatabaseConnector.main(DatabaseConnector.java:44)
    Does anyone have any ideas? Is it my code? Is there a different driver I should use? Any help would be greatly appreciated.

    Hello everyone. I am trying to make my first
    database connection to a mysql database with Java. I
    am using jdk 1.5.0, MySQL 4.1.11 nt, and I think I
    have the freshly downloaded driver
    C:\jdk1.5.0\jre\lib\ext\mysql-connector-java-3.0.16-ga
    -bin.jar" installed in the right spot. You shouldn't be putting that JAR in jre/lib/ext, even if you've found some docs to tell you to do it. Only language extensions (e.g., packages that begin w/javax) belong there.
    I get the following exception...
    java.sql.SQLException: No suitable driver
    Does anyone have any ideas? Is it my code? Is there
    a different driver I should use? Any help would be
    greatly appreciated.The driver is correct. The class loader found it, even though I think you should use the -classpath option to find the JAR.
    It's your code.
    What are you doing with all that RowSet stuff?
    This works. Study it:
    import java.sql.*;
    import java.util.*;
    * Command line app that allows a user to connect with a database and
    * execute any valid SQL against it
    public class DataConnection
        public static final String DEFAULT_DRIVER   = "sun.jdbc.odbc.JdbcOdbcDriver";
        public static final String DEFAULT_URL      = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\\Edu\\Java\\Forum\\DataConnection.mdb";
        public static final String DEFAULT_USERNAME = "admin";
        public static final String DEFAULT_PASSWORD = "";
        public static final String DEFAULT_DRIVER   = "com.mysql.jdbc.Driver";
        public static final String DEFAULT_URL      = "jdbc:mysql://localhost:3306/hibernate";
        public static final String DEFAULT_USERNAME = "admin";
        public static final String DEFAULT_PASSWORD = "";
        /** Database connection */
        private Connection connection;
         * Driver for the DataConnection
         * @param command line arguments
         * <ol start='0'>
         * <li>SQL query string</li>
         * <li>JDBC driver class</li>
         * <li>database URL</li>
         * <li>username</li>
         * <li>password</li>
         * </ol>
        public static void main(String [] args)
            DataConnection db = null;
            try
                if (args.length > 0)
                    String sql      = args[0];
                    String driver   = ((args.length > 1) ? args[1] : DEFAULT_DRIVER);
                    String url      = ((args.length > 2) ? args[2] : DEFAULT_URL);
                    String username = ((args.length > 3) ? args[3] : DEFAULT_USERNAME);
                    String password = ((args.length > 4) ? args[4] : DEFAULT_PASSWORD);
                    System.out.println("sql     : " + sql);
                    System.out.println("driver  : " + driver);
                    System.out.println("url     : " + url);
                    System.out.println("username: " + username);
                    System.out.println("password: " + password);
                    db = new DataConnection(driver, url, username, password);
                    System.out.println("Connection established");
                    Object result = db.executeSQL(sql);
                    System.out.println(result);
                else
                    System.out.println("Usage: db.DataConnection <sql> <driver> <url> <username> <password>");
            catch (SQLException e)
                System.err.println("SQL error: " + e.getErrorCode());
                System.err.println("SQL state: " + e.getSQLState());
                e.printStackTrace(System.err);
            catch (Exception e)
                e.printStackTrace(System.err);
            finally
                if (db != null)
                    db.close();
                db = null;
         * Create a DataConnection
         * @throws SQLException if the database connection fails
         * @throws ClassNotFoundException if the driver class can't be loaded
        public DataConnection() throws SQLException,ClassNotFoundException
            this(DEFAULT_DRIVER, DEFAULT_URL, DEFAULT_USERNAME, DEFAULT_PASSWORD);
         * Create a DataConnection
         * @throws SQLException if the database connection fails
         * @throws ClassNotFoundException if the driver class can't be loaded
        public DataConnection(final String driver,
                              final String url,
                              final String username,
                              final String password)
            throws SQLException,ClassNotFoundException
            Class.forName(driver);
            this.connection = DriverManager.getConnection(url, username, password);
         * Get Driver properties
         * @param database URL
         * @return list of driver properties
         * @throws SQLException if the query fails
        public List getDriverProperties(final String url)
            throws SQLException
            List driverProperties   = new ArrayList();
            Driver driver           = DriverManager.getDriver(url);
            if (driver != null)
                DriverPropertyInfo[] info = driver.getPropertyInfo(url, null);
                if (info != null)
                    driverProperties    = Arrays.asList(info);
            return driverProperties;
         * Clean up the connection
        public void close()
            close(this.connection);
         * Execute ANY SQL statement
         * @param SQL statement to execute
         * @returns list of row values if a ResultSet is returned,
         * OR an altered row count object if not
         * @throws SQLException if the query fails
        public Object executeSQL(final String sql) throws SQLException
            Object returnValue;
            Statement statement = null;
            ResultSet rs = null;
            try
                statement = this.connection.createStatement();
                boolean hasResultSet    = statement.execute(sql);
                if (hasResultSet)
                    rs                      = statement.getResultSet();
                    ResultSetMetaData meta  = rs.getMetaData();
                    int numColumns          = meta.getColumnCount();
                    List rows               = new ArrayList();
                    while (rs.next())
                        Map thisRow = new LinkedHashMap();
                        for (int i = 1; i <= numColumns; ++i)
                            String columnName   = meta.getColumnName(i);
                            Object value        = rs.getObject(columnName);
                            thisRow.put(columnName, value);
                        rows.add(thisRow);
                    returnValue = rows;
            else
                int updateCount = statement.getUpdateCount();
                returnValue     = new Integer(updateCount);
            finally
                close(rs);
                close(statement);
            return returnValue;
         * Close a database connection
         * @param connection to close
        public static final void close(Connection connection)
            try
                if (connection != null)
                    connection.close();
                    connection = null;
            catch (SQLException e)
                e.printStackTrace();
         * Close a statement
         * @param statement to close
        public static final void close(Statement statement)
            try
                if (statement != null)
                    statement.close();
                    statement = null;
            catch (SQLException e)
                e.printStackTrace();
         * Close a result set
         * @param rs to close
        public static final void close(ResultSet rs)
            try
                if (rs != null)
                    rs.close();
                    rs = null;
            catch (SQLException e)
                e.printStackTrace();
         * Close a database connection and statement
         * @param connection to close
         * @param statement to close
        public static final void close(Connection connection, Statement statement)
            close(statement);
            close(connection);
         * Close a database connection, statement, and result set
         * @param connection to close
         * @param statement to close
         * @param rs to close
        public static final void close(Connection connection,
                                       Statement statement,
                                       ResultSet rs)
            close(rs);
            close(statement);
            close(connection);
    }%

  • No suitable driver found for jdbc:mysql

    Running :
    Windows XP ver 5.1 on x86
    Java 1.6.0_03
    VM Java HotSpot Client VM 1.6.003-b05
    Java jdk1.6.0\jre
    MySQL ver 14.12 Distrib 5.0.45 for Win32 (ia32)
    NetBeans IDE 5.5.1 (Build 200704122300)
    Classpath set to:
    E:\Programfiler\Java\jre1.6.0_03\lib\ext\QTJava.zip;E:\Programfiler\MySQL\mysql-connector-java-5.1.5\mysql-connector-java-5.1.5-bin.jar
    MySQL (Connector/J driver)
    Can connect to database at Runtime folder in Netbeans IDE.
    Can see all tables and read them but when I run following code:
    try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (Exception e) {
    System.err.println(e.toString());
    I get following result;
    run:
    java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    java.sql.SQLException:
         ://localhost:3306/test
    at java.sql.DriverManager.getConnection(DriverManager.java:602)
    at java.sql.DriverManager.getConnection(DriverManager.java:185)
    at viewtable01.Main.main(Main.java:43)
    BUILD SUCCESSFUL (total time: 0 seconds)
    PLEASE HELP, I'M GOING NUTS

    I'M GOING NUTSI'm already there...
    Try this at a new command prompt (start~run: cmd)
    $ dir E:\Programfiler\MySQL\mysql-connector-java-5.1.5\mysql-connector-java-5.1.5-bin.jarDoes it exist?
    If not then fix your classpath.
    If so then start~run: notepad ConnectorTest.java
    import java.sql.Connection;
    import java.sql.DriverManager;
    public class ConnectorTest {
      public static void main (String[] args) {
        Connection conn = null;
        try {
          String userName = args[0];
          String password = args[1];
          String url = "jdbc:mysql://localhost/test";
          Class.forName("com.mysql.jdbc.Driver").newInstance ();
          conn = DriverManager.getConnection(url, userName, password);
          System.out.println ("OK");
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          if(conn != null)try{conn.close();}catch(Exception eaten){}
    javac -cp E:\Programfiler\MySQL\mysql-connector-java-5.1.5\mysql-connector-java-5.1.5-bin.jar ConnectorTest.java
    java -cp E:\Programfiler\MySQL\mysql-connector-java-5.1.5\mysql-connector-java-5.1.5-bin.jar ConnectorTest ${username} ${password}When you've got it working at the command line then you can work out how to specify the libraries in netbeans... it's not hard, and it's very well covered in the netbeans help.
    You do know that netbeans doesn't use the system classpath don't you... because the classpath really needs to be specified on a project by project basis, mainly to allow you deal with libraries which depend on particular versions of other libraries. Ant's dependancy on xalan and xerces is a notable example.
    IMHO (in my humble opinion) newbies are better of working at the command prompt whilst learning the java language. A modern IDE is a complex beasty in it's own right, which tends to distract your main focus, learning java. I'm not alone in this opinion. Take it or leave it.
    Cheers, Keith.
    Edited by: corlettk on Nov 10, 2007 11:53 PM

  • MYSQL JDBC NoClassDefFoundError: org/aspectj/lang/Signature

    i am trying to connect to a database via java using JDBC i have installed:
    jdk1.5.0_01
    mysql-connector-java-3.1.8-bin-g.jar
    MySQL Server 4.1
    Java works fine, MYSQL works fine from the command prompt but when it comes to testing using this simple java program
    public class JdbcExample1 {
    public static void main(String args[]) {
    Connection con = null;
    try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    con = DriverManager.getConnection("localhost", "username", "password");
    if(!con.isClosed())
    System.out.println("Successfully connected to MySQL server...");
    } catch(Exception e) {
    System.err.println("Exception: " + e.getMessage());
    } finally {
    try {
    if(con != null)
    con.close();
    } catch(SQLException e) {}
    this compiles fine but when run i get the following error message
    Exception in thread "main" java.lang.NoClassDefFoundError: org/aspectj/lang/Signature
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:164)
    at JdbcExample1.main(JdbcExample1.java:10)
    class path is set as .;C:\Program Files\Java\jdk1.5.0_01\jre\lib\ext\mysql-connector-java-3.1.8-bin.java
    any help or input on this error would be appreciated
    thanks in advanced Neil

    Hi, All:
    I just read this thread of discussion and got valueable info to solve my problem in a similar fashion. I'd suggest the last poster, Anil, to re-read the whole thread to correct the possible problems stated.
    I would just like to add my problem/solution scenario to this thread to share my experience. I assume that readers already went through the previous notes in this thread.
    #1. Space in Path:
    I installed
    MySQL DB server in: "C:\Program Files\MySQL\MySQL Server 4.1"
    MySQL JDBC Driver: D:\mysql\mysql-connector-java-3.1.8
    It seems to me that the DB server installed directory is not affected by whether there is a space in path name. The JDBC Driver path, on the other hand, does have the side effect of the space in path name when accessing by the Java client.
    #2. -g in JDBC Driver:
    I have been using the driver mysql-connector-java-3.1.8-bin.jar. However, right before I needed to create my ant build.xml configuration file (more details later), I thought the instruction asked me to use the mysql-connector-java-3.1.8-bin-g.jar (the debug version as kpreiser indicated), and therefore I got the now-well-known "org/aspectj/lang/Signature" error. After I removed that "-g" from the JDBC driver extression in my build.xml file, it then works well. (Great tip, kpreiser.)
    #3. Middlegen with Hibernate:
    My situation is a bit more complicated, but the issue of "org/aspectj/lang/Signature" error was the same (finally resolved in #2). I was trying to use Middlegen to re-generate my Hibernate map files from the data schema. (Hibernate is an open source tool that lets you create JavaBean source file from a Hibernate map file to map to a database table (see http://www.hibernate.org/ for more details.) Since I re-factored my data schema in the database, I needed to re-generate the Hibernate map files (from data schema) so that I can in turn use the map files to re-generate the JavaBean code. I wanted to use the Middlegen tool (see http://www.hibernate.org/98.html for more details) to re-generate the map files from database schema. However, in order to use Middlegen properly, you need to create the ant build.xml file to do that job. So I had to resort to MiddlegenIDE (see http://ultimania.org/middlegenide/ for more details) to help generate that build.xml file. (This is where I had the -g specified for the JDBC driver in the build.xml file that caused the problem.) Once that build.xml file is generated, the use of ant (a Java make tool) with the build.xml file can generate the hibernate map files. From these map files, JavaBean source files can be generated using Hibernate CodeGenerator.hbm2java tool. (There are several other useful tools in Hibernate too to convert the database ddl schema and the JavaBean source file.)
    Obviously, there are other approaches and tools that you can use (XDoclet for instance) for different situations, but I am only providing a high level overview on what you can do to be more productive if you are involved in a large and complicated project with Java/JDBC and ORM (Object/Relational Mapping).
    Item #3 may sound complicated at first, but it's worth the time to learn the tools and concept. Once you are familiar with these tools (Eclipse, Hibernate, Middlegen, Ant, etc.), you will become more productive in responding to the dynamic nature of the high-tech world where changing requirements are the only constant. I hope that these separate tools will become more integrated and easier to use in the future, but for now they do the job well.
    Thanks for the great tips and hope that this helps too.
    - Shuh

  • Connection mysql jdbc error ?

    I have program java likes this :
    import java.sql.*;
    public class LoadDriver {
        // Define the JDBC Driver and the database connection URL
        public static final String DRIVER = "com.mysql.jdbc.Driver";
        public static final String URL = "jdbc:mysql://localhost/java?user=test&password=test";
        public static void main(String args[]) {
            Connection conn = null;
    Statement select = null;
    ResultSet result = null;
            try {
                // load the driver dynamically
                Class.forName(DRIVER);
                // connect to the database
                conn = DriverManager.getConnection(URL);
                // perform a query. first create a Statement object from the connection
                select = conn.createStatement();
    // next execute a query (SQL string) and return the results in a ResultSet object
                result = select.executeQuery("select fname, lname from names order by lname, fname");
                // print out the results
                while(result.next()) {
                    String fname = result.getString("fname"); // note these match the columns in the
                    String lname = result.getString("lname"); // SELECT statement (fname, lname)
                    System.out.println(fname+" "+lname);
    // check if there was a problem executing the SQL statement
            catch (SQLException e) {
                System.err.println("SQL Exception: "+e.getMessage());
                System.exit(1);
    // if the JDBC driver is not in the CLASSPATH
            catch (ClassNotFoundException e) {
                System.err.println("Class not found:  "+e.getMessage());
                System.exit(1);
    // catch any other exceptions
            catch (Exception e) {
                System.err.println("Other Exception: ");
                System.err.println(e.getMessage());
                System.exit(1);
    // You want to close the connections no matter what happens!
    finally {
    try {
    // close the result, query, and database connection
    if (result != null) result.close();
                 if (select != null) select.close();
                if (conn != null) conn.close();
    catch (SQLException e) {
    // one of the new cases where it's OK to just eat exceptions or at the most log them
    System.err.println("Error closing connection: "+e.getMessage());
      but i get errror likes this :
    D:\Program Files\Java\jdk1.5.0_03\bin>javac LoadDriver.java
    D:\Program Files\Java\jdk1.5.0_03\bin>java LoadDriver
    Exception in thread "main" java.lang.NoClassDefFoundError: org/aspectj/lang/Sign
    ature
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:164)
    at LoadDriver.main(LoadDriver.java:20)
    D:\Program Files\Java\jdk1.5.0_03\bin>
    I place mysql.jar in
    - D:\Program Files\Java\jdk1.5.0_03\jre\lib\ext
    - D:\Program Files\Java\jdk1.5.0_03\lib
    - D:\Program Files\Java\jdk1.5.0_03\jre\lib
    and i make classpath to D:\Program Files\Java\jdk1.5.0_03\bin;D:\Program Files\Java\jdk1.5.0_03\jre\lib\ext\
    but it still doesn't work
    What must I do ?
    Thx 4 your reply

    Hello!
    I'm getting this same error message and i followed the code example as close as i could:
    Thanks for any help on this!
    bk
    set oldpath=%PATH%
    set JAVA_HOME=C:\jdk1.5.0_02
    set ANT_HOME=C:\ANT\apache-ant-1.6.5
    set PATH=C:\jdk1.5.0_02\bin;%ANT_HOME%\bin
    set CLASSPATH=.;C:\jdk1.5.0_02\lib;C:\MYSQL\mysql-connector-java-3.1.10\src\com\;C:\MYSQL\mysql-connector-java-3.1.10\src\org\;C:\MYSQL\mysql-connector-java-3.1.10\mysql-connector-java-3.1.10-bin-g.jar;
    http://www.developer.com/java/data/article.php/3417381#Critical_steps_in_using_JDBC
    import java.sql.*;
    public class Jdbc11 {
      public static void main(String args[]){
        System.out.println(
                      "Copyright 2004, R.G.Baldwin");
        try {
          Statement stmt;
          //Register the JDBC driver for MySQL.
          Class.forName("com.mysql.jdbc.Driver");
          //Define URL of database server for
          // database named mysql on the localhost
          // with the default port number 3306.
          String url =
                "jdbc:mysql://localhost:3306/mysql";
          //Get a connection to the database for a
          // user named root with a blank password.
          // This user is the default administrator
          // having full privileges to do anything.
          Connection con =
                         DriverManager.getConnection(
                                     url,"root", "");
          //Display URL and connection information
          System.out.println("URL: " + url);
          System.out.println("Connection: " + con);
          //Get a Statement object
          stmt = con.createStatement();
          //Create the new database
          stmt.executeUpdate(
                           "CREATE DATABASE JunkDB");
          //Register a new user named auser on the
          // database named JunkDB with a password
          // drowssap enabling several different
          // privileges.
          stmt.executeUpdate(
              "GRANT SELECT,INSERT,UPDATE,DELETE," +
              "CREATE,DROP " +
              "ON JunkDB.* TO 'auser'@'localhost' " +
              "IDENTIFIED BY 'drowssap';");
          con.close();
        }catch( Exception e ) {
          e.printStackTrace();
        }//end catch
      }//end main
    }//end class Jdbc11
    Exception in thread "main" java.lang.NoClassDefFoundError: org/aspectj/lang/Signature

Maybe you are looking for