Problem in accessing database using a java class

Hy Folks,
I have written a class to retrive data from data base and compiled it.when I said java QueryExample, I am getting the following error message.It is as below.
E:\>java QueryExample
Loading JDBC Driver -> oracle.jdbc.driver.OracleDriver
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286)
at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:120)
at QueryExample.<init>(QueryExample.java:37)
at QueryExample.main(QueryExample.java:129)
Creating Statement...
Exception in thread "main" java.lang.NullPointerException
at QueryExample.performQuery(QueryExample.java:70)
at QueryExample.main(QueryExample.java:130)
Now my question is can I run a jdbc program with out using any application server or webserver.
If I can , what are all the packeages I have to down load, and how to set their classpath.
Regards,
Olive.

My basic doubght is can we write a class like this.Here I give the sample code that I am using,,,, and using Oracle9i for Windows release 2 (9.2) .
// QueryExample.java
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
* The following class provides an example of using JDBC to perform a simple
* query from an Oracle database.
public class QueryExample {
final static String driverClass = "oracle.jdbc.driver.OracleDriver";
final static String connectionURL = "jdbc:oracle:thin:@localhost:1521:O920NT";
final static String userID = "scott";
final static String userPassword = "tiger";
Connection con = null;
* Construct a QueryExample object. This constructor will create an Oracle
* database connection.
public QueryExample() {
try {
System.out.print(" Loading JDBC Driver -> " + driverClass + "\n");
Class.forName(driverClass).newInstance();
System.out.print(" Connecting to -> " + connectionURL + "\n");
this.con = DriverManager.getConnection(connectionURL, userID, userPassword);
System.out.print(" Connected as -> " + userID + "\n");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
* Method to perform a simply query from the "emp" table.
public void performQuery() {
Statement stmt = null;
ResultSet rset = null;
String queryString = "SELECT name, date_of_hire, monthly_salary " +
"FROM emp " +
"ORDER BY name";
try {
System.out.print(" Creating Statement...\n");
stmt = con.createStatement ();
System.out.print(" Opening ResultsSet...\n");
rset = stmt.executeQuery(queryString);
int counter = 0;
while (rset.next()) {
System.out.println();
System.out.println(" Row [" + ++counter + "]");
System.out.println(" ---------------------");
System.out.println(" Name -> " + rset.getString(1));
System.out.println(" Date of Hire -> " + rset.getString(2));
System.out.println(" Monthly Salary -> " + rset.getFloat(3));
System.out.println();
System.out.print(" Closing ResultSet...\n");
rset.close();
System.out.print(" Closing Statement...\n");
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
* Close down Oracle connection.
public void closeConnection() {
try {
System.out.print(" Closing Connection...\n");
con.close();
} catch (SQLException e) {
e.printStackTrace();
* Sole entry point to the class and application.
* @param args Array of String arguments.
* @exception java.lang.InterruptedException
* Thrown from the Thread class.
public static void main(String[] args)
throws java.lang.InterruptedException {
QueryExample qe = new QueryExample();
qe.performQuery();
qe.closeConnection();
}

Similar Messages

  • Setting System DSN for MS Access Database using Java Code

    How to set the system DSN for Access database using Java Code at runtime....???
    Replies are deeply appreciated...

    I found a 3rd Party MS Access JDBC Driver from a Google search. I downloaded and tried the free trial version. It worked fine but we opted not to purchase the full version and went a different route. If you don't find it, let me know and I'll see if I can track down the name of the product we tested.

  • Problems converting access database to excel

    is there any method to convert access db to excel spreadsheet.
    currently i'm using a 'cheat' way of retrieving the results to a table and convert to excel using this:
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition","attachment; filename=\"file.xls\";");
    the problem is that i need to delete the records in the database after saving the the excel file. this method does not let me perform response.sendRedirect() method after saving as excel. so, after i retrieve the results into a table, i delete the records in the database and prompt the user to save the excel file. this is risky cos if the user select cancel when prompted to save, the records in the databse will long be gone.
    i need help if anyone could suggest a solution to this.
    1. another method to convert access db to excel spreadsheet , or
    2. the excel file will be saved automatically without having the user to click to save, or
    3. to be able to get to delete the db records after saving.
    i really need the help from you people. thanks.

    I find your problem description confusing.
    Here's what it sounds like you're saying:
    You've got records in an Access database to start with. A user makes a request to see records in a browser. You've got a servlet that queries the Access database using JDBC, turns the result set into a CSV file, sets the content type to "application/vnd.ms-excel", and then displays the response as an MS Excel spreadsheet in the browser.
    So far, so good?
    That sounds like one use case to me - call it "Query Database For Records".
    Then it sounds like you want to implement another use case - call it "Modify Database". You'd like to be able to let the client manipulate the Excel data you've sent down and then resynch with the database when they say they're done.
    Again, okay?
    If that's true, treat them like two separate cases. It sounds like you want to do a multipart file upload of the Excel data where you'd have your servlet take the uploaded data and insert it back into the Access database.
    If I understand you correctly, Access is your persistence mechanism. I don't understand why you'd want to update Access AND save the Excel file. I read this as "I want to have one data source of record with the latest info, and I happen to like sending it down to clients in an Excel spreadsheet because that's what they're used to seeing."
    I'm sure this doesn't help you solve your problem yet, but it might help my understanding of what you're really trying to do here. - MOD

  • Integrate 300 MS Access Databases using ODI

    Hi All,
    I am trying to integrate data between 300 similar MS Access databases using ODI. All the source databases have exactly the same data structures. I have done a POC for 3 databases by creating interfaces and could integrate the data between them successfully.
    Now that the project is approved ; Going forward I need to integrate data from 297 MS Access databases, so I need to run the same set of Interfaces on 297 source MS Access Databases with Target DB being the same.
    This integartion work could be labourious as I need to copy 7 interfaces on 297 databases - IS THERE ANY EASY SOLUTION FOR THIS PROBLEM.
    Some one suggested me to use Dynamic Variables in the TOPOLOGY to access all the MS Access databases - BUT NOT SURE IF THAT WORKS.
    APPRECIATE your suggestions.
    Thanks & Regards
    Kay

    The issue you face here is that the Access database is connected to through the JDBC-ODBC bridge to the Access ODBC database driver. You will need to have a separate DSN defined for each of the access databases, if you want to address each individually.
    An alternative approach is to have one DSN set up, one entry in ODI's topology, one interface etc, and each file you wish to use, you rename to a given name first. Thus, when ODI tries to access the database, the ODBC driver finds the then current file. Note that ODI keeps the database connection for the duration of a SESSION, so if you wanted to process all 300 files sequentially, then you would need to run separate sessions for each of the file executions.
    I think this will give you the solution you require without resorting to variables.

  • How do I open a pdf stored in a Microsoft Access database using Visual Basic studios 2012

    Currently I am unable to find a valid method of being able to open a pdf stored in a Microsoft Access database using Visual Basic studios 2012. I've tried displaying the entire database on a form, but when I do this all the other columns show up with
    the correct data besides the one containing the pdf's, it just displays <binary data> in each row down the column. I also tried another method with which you use the database as a dataset and can drag and drop the rows and columns into the form, which
    again works for all the other columns besides the one containing the pdf's but this time I'm unable to interact with the column  at all. 
    Not too sure if this is in the correct place, but any answers or help would be appreciated. Cheers.

    Alex,
    This forum is dedicated to Project and Project Server. You might get better response, if you post to a Visual Basic forum. Here are couple I could find. 
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=vbgeneral%2Cvblanguage&filter=alltypes&sort=lastpostdesc
    Cheers,
    Prasanna Adavi, Project MVP
    Blog:
      Podcast:
       Twitter:   
    LinkedIn:
      

  • Using normal java classes to access database

    Dear friends,
    Is it a good practice to make database calls from a normal java class within J2EE environment.
    What I meant by a normal java class is a class which is not an enterprise bean.
    Best Regards,
    Chamal.

    it is quite normal.
    If you make your own DAOs, it may not be efficient/generic.
    JSP/Servlets can use Hibernate (which is a set of POJOs) to access DB. Thus you have a J2EE environment using a very matured DB access methodoloy, and doing away with Enterprise bean.
    regards

  • How to use Forms Default Database Connection in java class

    When a form based application is started, a connection is made with underlying database. This is the Default (Primay) Database Connection.
    The problem is I have some of my business logic implemented in a java class. In this class I have to make a another connection with the same database. What I want to do is to use the original Database Connection in the java class. In this I may avoid the overhead of reconnection.
    Could anyone pls guide me in this way...

    you can't share the forms connection. Sorry :(

  • Help me which JNDIFactory to use to access EJB from a java class of JAR

    I am confused in understanding the different JNDI factories
    RMIInitialContextFactory, ApplicationInitialContextFactory and ApplicationClientInitialContextFactory
    And the different namespaces like global, container local and component local.
    Especially is there any relationship between the JNDI factories and the namespaces?
    Or are they related to the deployment descriptors.
    Because in application specific deployment descriptors (orion-ejb-jar.xml), we just map the JNDI location with the object (or its reference from ejb-jar.xml). We dont specify it can be accessed from this factory or that.
    Shall we access an EJB from using any JNDI factory?
    Specifically, I am stuck with what Factory to use to access an EJB from a Java class in a library (jar). The JAR is packaged with the EAR which contains the EJB Jar that I am trying to access.
    THANK YOU

    Ed,
    As Robin said, I think you need code similar to this:
    Context c = new InitialContext();
    Object o = c.lookup("java:comp/env/Name");where Name is the name of your EJB as it appears in the "ejb-jar.xml"
    deployment descriptor XML file.
    Good Luck,
    Avi.

  • Problem in connect database using applet

    hi
    please
    i want open database in page html with use Applet
    i use this code but database not work in the my page
    if this code have problem
    please correct this code to open database in page html
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con = DriverManager.getConnection(
    "jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb);DBQ=C:\\hwzyfa.mdb ");
    sta = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_UPDATABLE);
    res = sta.executeQuery("select * from aha");
    this is my code
    package orcle;
    import java.sql.*;
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    <applet code="test.class" width=200 height=200>
    </applet>
    public class Applora extends Applet implements ActionListener
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    String str=null;
    TextArea ta;
    public void init()
    ta= new TextArea(10,30);
    add(ta);
    Button b1 = new Button(">>");
    add(b1);
    b1.addActionListener(this);
    ta.setText("Initialization...\n");
    public void start() {java.applet.AudioClip a=  Applet.newAudioClip(Applora.class.getResource("a.mid"));
       a.play();
    public void actionPerformed(ActionEvent ae)
    ta.appendText("Inside actionPerformed\n");
    try
    ta.appendText("Inside try block\n");
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    ta.appendText("Class loaded\n");
    /********** upto this point it works fine **************/
    con=DriverManager.getConnection("jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb);DBQ=C:\\hwzyfa.mdb ");
    ta.appendText("Connection created\n");
    stmt=con.createStatement();
    ta.appendText("Statement created\n");
    rs=stmt.executeQuery("select * from aha");
    ta.appendText("Resultset created\n");
    while(rs.next())
    str=str+rs.getString(2)+" "+"\n";
    //str=str+rs.getString(2)+" "+"\n";
    ta.appendText(str);
    con.close();
    stmt.close();
    rs.close();
    }catch(ClassNotFoundException cnfe){System.out.println("Class Not found "+cnfe.getMessage());}
    catch(SQLException sqle){System.out.println("SQL Exception "+sqle.getMessage());ta.setText(sqle.getMessage());}
    catch(Exception e){ta.setText(e.getMessage());e.getMessage();}
    }

    i want access to database in page html with use AppletFirst of all, that doesn't make any sence, if it's a single user application make it a java
    application.
    If it's a multu user application make it a client server where the web server connects to
    the database when the client requests a connection.
    When the applet connects to the database any client running the applet needs a
    connection to your database server, the client needs the jdbc drivers and the client's
    jre needs to find them (set classpath with runtime parameters or set the classes in
    javadir lib). After that the client needs to change thiere java.policy or you need to sign
    the applet.
    Needless to say that's a lot of trouble. And if you go through all that trouble the client
    can de-compile your applet and see the connection to the database server and the
    server name. Now the client can destroy your database or worse see date it is not
    supposed to see.
    Since you are a brainless ... who needed to post this question 6 times did not respond to any of my post in your other threads I can just say good luck with your problem.

  • AES Algorithm error when trying to encrypt using stored Java class.

    Dear All,
    We have a specific reuirement where in we cannot use DBMS_CRYPTO package to encrypt/decrypt data using AES Algorithm
    So I am trying to use a stored Java class and I am getting "AES algorithm not available".
    I am using Oracle 10gR2 standard edition.
    Below is my code
    1. Stored Java class
    2. Stored function to access the above Java class.
    3. Test anonymus PL/SQL to test above code.
    Please help me finding the problem why I am getting "AES algorithm not available" error when I call stored Java class in Oracle.?
    **** If I use "DES" algorithm, it works. Also the Java code works well if I execute it as normal Java class from Eclipse.
    I verified the java.security file in jre/lib/security and I see that there is provider entry for SunJCE.
    The jre version in Oracle is 1.4.2.
    I appreciate your help.
    Thanks,
    Priyanka
    Step1: Stored java class to encrypt and decrypt data
    CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "EncryptUtil" AS
    import java.security.Key;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    public class EncryptUtil
         public static String encrypt(String inStr)
         String outStr = "Test data 123";
    try
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128);
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted =
    cipher.doFinal(inStr.getBytes());
    outStr =new String(encrypted);
    catch (Exception e)
         outStr = outStr + "exception thrown::" + e.getMessage();
    e.printStackTrace();
    return outStr;
    Step2: Stored function to access above stored java class.
    CREATE OR REPLACE FUNCTION SF_ENCRYPTUTIL(
    pKey1 VARCHAR2
    ) RETURN VARCHAR2 AS
    LANGUAGE JAVA NAME 'EncryptUtil.encrypt(java.lang.String ) return java.lang.String';
    Step3: Test encryption and descryption
    DECLARE
    outstr VARCHAR2(2000);
    BEGIN
    DBMS_OUTPUT.PUT_LINE('outstr-->' || SF_ENCRYPTUTIL('12345'));
    END;
    Below code example using DBMS_CRYPTO. This works, but we do not want to use this.
    declare
    l_in_val varchar2(2000) := 'Test data 123';
    l_mod number := dbms_crypto.ENCRYPT_AES128
    + dbms_crypto.CHAIN_CBC
    + dbms_crypto.PAD_PKCS5;
    l_enc raw (2000);
    l_enc_key raw (2000);
    l_dec raw (2000);
    begin
    l_enc := dbms_crypto.encrypt
    UTL_I18N.STRING_TO_RAW (l_in_val, 'AL32UTF8'),
    l_mod,
    HEXTORAW('156ae12300ccfbeb48e43aa016febb36'),
    HEXTORAW('001122230405060708090a0b0c0d0e0f')
    dbms_output.put_line ('Encrypted='||l_enc);
    end;
    Edited by: user5092433 on Sep 10, 2009 12:26 AM

    I guess I'd be a bit curious about why you can't use a DBMS_CRYPTO solution that provides identical output. It seems odd to want to have a procedure running inside Oracle and then dictate that it has to be Java and not PL/SQL...
    I verified the java.security file in jre/lib/security and I see that there is provider entry for SunJCE.
    The jre version in Oracle is 1.4.2.Which java.security file are you talking about? The JVM that is inside the Oracle database does not and can not use configuration files that are outside the database. I suspect when you talk about files and paths that you're looking at a JVM outside the database, which is not the JVM that your Java stored procedure would be using.
    Looking at the error, my assumption is that some JAR file needs to be loaded into the internal JVM in order for the AES algorithm to be available. But I'm unfortunately not familiar enough with these classes to say what that would be.
    Justin

  • Java, access database( mdb) and java.sql.date

    I having a problem querying my access database with user specified date the code is as follows
    //get results of income from database with respectto dates
         //so u first create the sql.date instances
         private void getResults(){
         String text1=from.getText();//text input is like this 01-01-2005
              String text2=to.getText();
         Date d1=new Date(Integer.parseInt(text1.substring(6)),Integer.parseInt(text1.substring(3,5)),Integer.parseInt(text1.substring(0,2)));
         JOptionPane.showMessageDialog(this,d1.toString());//traces date with 1900 added to year and 1 added to month
         try{
              //custom class DataSource used to connect to database
              Connection conn=DataSource.getConnection("RealFotoInc");
              PreparedStatement ps=conn.prepareStatement("select * from Members where date=?");
              ps.setDate(1,d1);
              ResultSet rs=ps.executeQuery();
              while(rs.next()){
                   System.out.println("going");
                   System.out.println("trial"+rs.getString(3));
         }catch(Exception se){
              JOptionPane.showMessageDialog(this,se);
         }and it prints out nothing I dont know what is wrong

    Whoever put that comment in there about "1900" and so on knew what had to be done. That "Date" class must be "java.sql.Date"; go and read the API documentation of that constructor you are using there. Then adjust the parameters you are passing to it accordingly.

  • Creating a new access database using JDBC

    Hi Forum,
    I have a problem in hand. Let me describe the problem:
    I want to create an "access database" from java at runtime. "Access database" is file based, so for a database named test, it will have a file test.mdb.
    Now, everything's sweet and wonderful, if somebody creates an "empty access database" at the client machine and i then connect to it and create the tables i require.
    But the issue is i want to create the database at runtime (the database name and tables are determined at runtime).
    Using the JDBC:ODBC bridge driver , i am able to connect to an existing database, but any "create database" statements are not supported.
    A last ditch solution would be that i create an empty database using access and copy the file contents in the SQL server database as a a blob object. Then when i want to create a new access database at runtime, i create a file in a particular folder , with an .mdb
    extension, copy the file contents from the SQL server (i also have an SQL server connection) BLOB object, and then try to connect to the
    .mdb file.
    But this approach seems a "quick hack" and can have problems (which i can't see as of now).
    Can you suggest a better alternative for the problem.
    See the Java Sun forum at this address for a discussion of a similar problem, but sadly with no solution.
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=484731

    I have an applet that was previously connected to Oracle 9i. I am faced with connecting to MS Access temporarily for testing purposes.
    I have been unable to successfully code connection in java. I have set up the DSN and can access in SQL Worksheet in JDev.
    I saw your question regarding creating an access db, and thought you might be so kind as to help me code the connection to access!!!!
    Any help you could provide would be greatly appreciated. I have a huge application to finish with alot of sqlj already completed. Connectivity is not my area of expertise!
    Any help you could provide would be greatly appreciated!!!
    I am not sure if I have to use bridge? Am I progressing in right direction to migrating to SQL Server if need be?

  • Connect to a remote MS Access database using RmiJdbc

    Hello,
    I want to access a remote MS Access database from oracle stored procedures.
    Does anyone know how i can load the RmiJdbc driver using the loadjava command or with any other way.
    Because when i try to load RmiJdbc.zip using the loadjava command I am getting the error:
    ORA-29533:attempt to overwrite class or resource string while defining or compiling scott.TestClient
    this error is occured for multiple files...
    I don't know how to delete this classes.
    Because this error occured and the first time i tried to load Rmijdbc driver.
    and when i use the dropjava command to drop it,and then load it again the same error occures.
    Can anyone help me how to load this driver?
    Please answer because i need it as soon as possible.
    Thanks

    Hi,
    try this.
    String s = "UPDATE AGENT SET afname='test',alname='u',city='d',AGENT.[percent]=1 WHERE aid=23";
    -------->AGENT.[percent]

  • How to access variables declared in java class file from jsp

    i have a java package which reads values from property file. i have imported the package.classname in jsp file and also i have created an object for the class file like
    classname object=new classname();
    now iam able to access only the methods defined in the class but not the variables. i have defined connection properties in class file.
    in jsp i need to use
    statement=con.createstatement(); but it shows variable not declared.
    con is declared in java class file.
    how to access the variables?
    thanks

    here is the code
    * testbean.java
    * Created on October 31, 2006, 12:14 PM
    package property;
    import java.beans.*;
    import java.io.Serializable;
    public class testbean extends Object implements Serializable {
    public String sampleProperty="test2";
        public String getSampleProperty() {
            return sampleProperty;
    }jsp file
    <%@ page contentType="text/html;charset=windows-1252"%>
    <%@ page import="java.sql.*,java.util.*"%>
    <html>
    <head>
    <title>Schedule Details</title>
    </head>
    <jsp:useBean id="ConProp" class="property.testbean"/>
    <body>
    Messge is : <jsp:getProperty name="msg" property="sampleProperty"/>
    <%
      out.println(ConProp.sampleProperty);
    %>
    </body>
    </html>out.println(ConProp.sampleProperty) prints null value.
    is this the right procedure to access bean variables
    thanks

  • How to insert date into ms access database using sql query in servlet

    sir all thing is working well now only tell me how we can insert date into ms access database which is input by user .
    insert into db2(bookname,studentname,date) values('"+bname+"','"+sname+"',date_format)";{code}
    or either the system date is inserted with query .
      plz help me
    thanx                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    bhavishya wrote:
    sir all thing is working well now only tell me how we can insert date into ms access database which is input by user .
    insert into db2(bookname,studentname,date) values('"+bname+"','"+sname+"',date_format)";{code}
    or either the system date is inserted with query .
    plz help me
    thanxAnd that SQL statement is another reason to use PreparedStatement. I assume bname and sname are input from some form? Well, if that's the case, simply inserting them into SQL by simple String concatenation is just begging for all sorts of problems. What if there is an apostrophe in the entry? Broken Statement. Worse, it's a wide open invitation to an SQL Injection attack.

Maybe you are looking for