Database DAO - JDBC Query Class - Code review please

I use the following class (Database.java) as a DAO for handling all database calls. The class works. You can use this if you're looking for a DAO solution (i.e. a way to query databases using connection pools / JNDI). I am looking for some suggestions on improving this class. Can you help? I.e. suggestions for improving SELECT speed, logic? The class is used by a moderately heavily used Web application (ca. 2000 - 3000 queries a day - so not too much) on a Sun Web Server system.
This class had the following interfaces:
getErrors() // for retrieving any errors that occurred during an query
setSql() // one way to set the SQL that must be run
setDbName() // one way to set the JNDI name of the database resource
getInsertDelete() // run the INSERT/DELETE statement that was provided with setSql
getInsertDelete(String givenSql, String givenDb) // run with provided sql and db
getClobInsert(String givenSql, String givenDb, Hashtable clobHash, String identifierSql) // clobHash contains the column name and the value (which is a string over 4000 chars). Identifier SQL is the SQL for identifying the row, into which the Clob must be inserted. This interface is specific to Oracle.
getSelect() // Query database with set SQL. Return as a vector of hashes so I can close connection.
getSelect(String givenSql, String givenDb) // select with given sqlAnd here is the full class. I know, this is a weird post, but we don't really have a code review process here at work, and I don't have a specific problem. Just want some feedback concerning the way I query our databases. So, any tips or comments are welcome.
package melib.network;
import java.io.Writer;
import java.io.StringReader;
import java.io.IOException;
import java.util.Vector;
import java.util.Hashtable;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Clob;
import javax.sql.DataSource;
import javax.naming.InitialContext;
import melib.system.PropertiesReader; // This is just a simple class for pulling values from a .properties file
* Manages database connections.
* @author jetcat33
* @version 2.0, 2006-07-09
public class Database {
    protected String sql = "";
    protected String dbName = "";
    private StringBuffer errors = new StringBuffer();
    /** Creates a new instance of Database */
    public Database() {
     * Check completeness of data
     * for example to check if dbname given or
     * sql given or to make sure that yikes
     * used instead of sccweb in test conditions
    protected boolean checkData(){
        if(dbName.equals("") || sql.equals("")){
            Email.sendMail(PropertiesReader.getValue("statusEmail"),null,"MelibLibraryError","melib error: [Database]","No database selected for query (db: "+dbName+" or sql not included (sql: "+sql+")");
            setErrors("No database selected for query (db: "+dbName+" or sql not included (sql: "+sql+")");
            return false;
        }else{
            return true;
     * Sets and gets errors resulting from
     * exceptions - otherwise would have to
     * somehow include errors in the results
     * that are returned but that would include
     * other more complicated stuff.
    private void setErrors(String e){
        errors.append("\n"+e);
    public StringBuffer getErrors(){
       return errors;
     * Setter for the sql variable.
     * @param givenSql The sql required to process
    public void setSql(java.lang.String givenSql) {
        sql = givenSql;
     * Sets the dbName needed to commect
     * to the correct database.
     * @param givenDbName Name of the database - name and connections specified within this class
    public void setDbName(java.lang.String givenDbName) {
        dbName = givenDbName;
     * Processes Insert and Delete requests with given SQL and DB Name.
     * @param givenSql
     * @param givenDbName
     * @return String Number of rows affected
    public String getInsertDelete(String givenSql, String givenDbName){
        sql = givenSql;
        dbName = givenDbName;
        return getInsertDelete();
     * Takes care of insert, update and delete requests.
     * Must have set both dbName as well as the sql String.
     * Will return number of rows affected as String.
     * @return String Number of rows affected
     * @exception Exception
    public String getInsertDelete() {
        int returnValue = 0;
        if(checkData()){
            Connection conn = null;
            InitialContext initContext = null;
            DataSource source = null;
            Statement stmt = null;
            try{
                // Get connection from configured pool
                initContext = new InitialContext();
                source = (DataSource) initContext.lookup("java:comp/env/jdbc/" + dbName);
                conn = source.getConnection();
                if(conn != null){
                    stmt = conn.createStatement();
                    returnValue = stmt.executeUpdate(sql);
            }catch (Exception e){
                Email.sendMail(PropertiesReader.getValue("statusEmail"),null,"MelibLibraryError","melib error: [Database.getInsertDelete]","getInsertDelete Exception: "+e.toString()+"\nWith: "+sql);
                setErrors(e.toString());
            }finally{
                try{
                    stmt.close();
                }catch(Exception e){
                    e.printStackTrace();
                try{
                    conn.close();
                }catch(Exception e){
                   e.printStackTrace();
                try{
                    initContext.close();
                }catch(Exception e){
                    e.printStackTrace();
        return returnValue+"";
     * Processes Insert requests for SQL containing CLOBS
     * @param givenSql
     * @param givenDbName
     * @param clobHash Contains column name of clob and clob text
     * @param identifierSql Contains SQL to identify the just entered SQL so the clobs can be filled in.
     * @return String Number of rows affected
    public String getClobInsert(String givenSql, String givenDbName, Hashtable clobHash, String identifierSql){
        sql = givenSql;
        dbName = givenDbName;
        String returnValue="";
        int rv = 0;
        if(checkData()){
            Connection conn = null;
            InitialContext initContext = null;
            DataSource source = null;
            Statement stmt = null;
            try{
                // Get connection from configured pool
                initContext = new InitialContext();
                source = (DataSource) initContext.lookup("java:comp/env/jdbc/" + dbName);
                conn = source.getConnection();
                if(conn != null){
                    conn.setAutoCommit(false);
                    stmt = conn.createStatement();
                    rv = stmt.executeUpdate(sql); // write first time
                    // Now get and overwrite "EMPTY_CLOB()"
                    ResultSet lobDetails = stmt.executeQuery(identifierSql);
                    ResultSetMetaData rsmd = lobDetails.getMetaData();
                    if(lobDetails.next()){
                        for(int i = 1; i <= rsmd.getColumnCount(); i++){
                            if(clobHash.get(rsmd.getColumnName(i))!=null && !clobHash.get(rsmd.getColumnName(i)).equals("")){
                                Clob theClob = lobDetails.getClob(i);
                                Writer clobWriter = ((oracle.sql.CLOB)theClob).getCharacterOutputStream();
                                StringReader clobReader = new StringReader((String) clobHash.get(rsmd.getColumnName(i)));
                                char[] cbuffer = new char[30* 1024]; // Buffer to hold chunks of data to be written to Clob, the slob
                                int nread = 0;
                                try{
                                    while((nread=clobReader.read(cbuffer)) != -1){
                                        clobWriter.write(cbuffer,0,nread);
                                }catch(IOException ioe){
                                   //System.out.println("E: clobWriter exception - " + ioe.toString());
                                }finally{
                                    try{
                                        returnValue+=" Writing: "+rsmd.getColumnName(i);
                                        clobReader.close();
                                        clobWriter.close();
                                    }catch(IOException ioe2){
                                        //System.out.println("E: clobWriter close exception - " + ioe2.toString());
                    conn.commit();
            }catch (Exception e){
                Email.sendMail(PropertiesReader.getValue("statusEmail"),null,"MelibLibraryError","melib error: [Database.getClobInsert]","getClobInsert Exception: "+e.toString()+"\nWith: "+sql+"\nAND\n"+identifierSql);
                setErrors(e.toString());
            }finally{
                try{
                    stmt.close();
                }catch(Exception e){
                    e.printStackTrace();
                try{
                    conn.close();
                }catch(Exception e){
                   e.printStackTrace();
                try{
                    initContext.close();
                }catch(Exception e){
                    e.printStackTrace();
            returnValue=rv+" "+returnValue;
        return returnValue;
     * Takes care of Select statements.
     * Must have set both dbName as well as the sql String.
     * Will return a vector.
     * @return Vector of Hashes containing the Results of the query
     * @exception SQLException
     * @exception Exception
    public Vector getSelect(){
        Vector returnValue = new Vector();
        if(checkData()){
            Connection conn = null;
            InitialContext initContext = null;
            DataSource source = null;
            ResultSet result = null;
            ResultSetMetaData rsmd = null;
            Statement stmt = null;
            try{
                // Get connection from configured pool
                initContext = new InitialContext();
                source = (DataSource) initContext.lookup("java:comp/env/jdbc/" + dbName);
                conn = source.getConnection();
                if(conn != null){
                    stmt = conn.createStatement();
                    result = stmt.executeQuery(sql);
                    rsmd = result.getMetaData();
                    while(result.next()){
                        Hashtable hash = new Hashtable();
                        for(int i = 1; i <= rsmd.getColumnCount(); i++){
                            if(result.getString(i) != null){
                                hash.put(rsmd.getColumnName(i),result.getString(i));
                            }else{
                                hash.put(rsmd.getColumnName(i),"");
                        returnValue.addElement(hash);
            }catch (Exception e){
                Email.sendMail(PropertiesReader.getValue("statusEmail"),null,"MelibLibraryError","melib error: [Database.getSelect]","getSelect Exception: "+e.toString()+"\nWith: "+sql);
                setErrors(e.toString());
            }finally{
                try{
                    result.close();
                }catch(Exception e){
                    e.printStackTrace();
                    setErrors(e.toString());
                try{
                    stmt.close();
                }catch(Exception e){
                    e.printStackTrace();
                    setErrors(e.toString());
                try{
                    conn.close();
                }catch(Exception e){
                   e.printStackTrace();
                   setErrors(e.toString());
                try{
                    initContext.close();
                }catch(Exception e){
                    e.printStackTrace();
                    setErrors(e.toString());
        return returnValue;
     * Takes care of Select statements with given SQL.
     * Must have set both dbName as well as the sql String.
     * Will return a vector.
     * @return Vector with Results of the query
     * @exception SQLException
     * @exception Exception
    public Vector getSelect(String givenSql, String givenDbName){
        sql = givenSql;
        dbName = givenDbName;
        return getSelect();
}Thank you,
dailysun

too much code that's repeated. refactor all the code you have for closing resources into a utility class and simply call its methods.
your dao creates the connection, so it can't participate in a transaction. if there are several daos that should be one unit of work, you can't manage it with this framework.
transactions are under the control of a service layer. I think it's better to have the service object get the connection, pass it to all the DAOs needed for that unit of work, and then have the service close it.
e-mailing errors? I don't like it. if you have 2-3K queries a day failing because the database you'll have 2-3K e-mails to delete. better to log messages. if you really want e-mail, you can have Log4J add an e-mail appender. at least that way it's configurable outside the code.
CRUD operations without an UPDATE? You're missing something important.
What if I don't want to get the database from a JNDI datasource? Now you can't use this DAO without an app server.
Your error messages are less informative than a stack trace. Why not throw an exception with detailed info?
have a look at Spring and how it handles persistence. if you insist on writing your own, might want to look at Spring. Rod Johnson has developed a much better, more general way to handle persistence.
http://www.springframework.org
You return a Vector of Hashtables for queries? Two old-school data structures. You understand the implication of choosing those, right? I'd recommend that you change that to a List of Maps. Let the concrete types be ArrayList and HashMap. Interfaces are preferred, because they let you change the implementation without affecting clients. Vector and Hashtable are synchronized by default; ArrayList and HashMap are not. Synchronization is thread safe but slower.
I understand why you chose to return Vector, because you wanted something general that wouldn't force you to deal with object-relational mapping. This way you can just worry about ResultSetMetaData.
A Vector of Hashtables is a row-based view of the ResultSet (one Hashtable per row). Sometimes a column based view can be more convenient. Then it's a Map of Lists.
You gave it a good try, but I think there's a lot of room for improvement.
%

Similar Messages

  • Get ID from database, launching a query from code and set NOCOUNT clause

    Hello,
    I need to extract some id from some table in mydatabase. I launching query from code.
    I would like to know if it is correct what I do
    SET NOCOUNT ON
    SELECT ID FROM tblID
    SET NOCOUNT OFF
    it is right to set nocount on at the beginning and if you need to reset it in the end.
    Many thanks
    www.Photoballot.net

    When SET NOCOUNT is ON, the count is not returned. When SET NOCOUNT is OFF, the count is returned.
    SET NOCOUNT ON prevents the sending of DONE_IN_PROC messages to the client for each statement in a stored procedure. For stored procedures that contain several statements that do not return much actual data, or for procedures that contain Transact-SQL loops,
    setting SET NOCOUNT to ON can provide a significant performance boost, because network traffic is greatly reduced.
    It won't have any major impact in your case however like they say its good to have it.
    To read more about see -
    http://msdn.microsoft.com/en-us/library/ms189837.aspx
    If this post answers your query, please click "Mark As Answer" or "Vote as Helpful".

  • To view database Java Source and Class code in SQL Developer - Do this...

    I've wanted something like this for a while.. Hope this helps someone else...
    Make a master detail report...
    1. Click the reports tab.
    2. Right click on "user defined reports" and select "add report"
    3. Type "Java Source Object and Class Code" into the name field.
    4. Make sure "Style" is set to "Table".
    5. Paste this code into the "SQL" window.
    select OBJECT_NAME, OBJECT_TYPE, to_char(created,'DD-MON-YYYY HH24:MI:SS') Created, to_char(LAST_DDL_TIME,'DD-MON-YYYY HH24:MI:SS') "Last DDL", STATUS
         from user_objects
        where object_type in ('JAVA SOURCE')
        order by object_name6. Click "Add child"
    7. Make sure "Style" is set to "Code" in the child.
    8. Paste the following code into the SQL window of the child.
    select text from user_source where name = :OBJECT_NAME order by line9. Click Apply..
    10. Enjoy...
    no semicolons after the sql....
    Message was edited by:
    slugo

    Mark,
    Thanks Check this out people can now subscribe to the public reports out no the exchange.
    http://krisrice.blogspot.com/2007/10/marks-post-on-forums-got-me-to-do.html
    -kris

  • Reports 9i Jdbc Query dialog box

    Hi,
    Is it possible to base a report on a pl/sql stored procedure in Reports builder 9i environment using with jdbcpds.If possiblePlease provide step by step details and how we can call that particular procedure in JDBC query dailog box.
    Please provide detailed example program asap.
    Thanks&Regards,
    Raghu

    Hi Raghu
    Indeed yes. You can base your report on PL/SQL stored procedure. For this to work with JDBC query, your stored procedure must return records.
    Refer Reports help on OTN for more information.
    Regards
    Sripathy

  • JDBC query with Sybase database

    Hi Folks,
    I am working with Oracle 9i Reports Builder connecting to Sybase database using jdbc-odbc driver type.
    I could connect to the database, use a simple query and generate reports.
    Problem is only when, I use a variable in WHERE clause and have
    1. group functions in SELECT statements (i.e. sum(), count()..)
    2. NOT IN operations in one of conditions
    Error message was thrown saying "Incorrect Syntax near ':.' "
    (I declare a variable in USER PARAMETER and use the same in WHERE clause by refering say "where trandate=:m_trandate".)
    Though there is no syntax error AT ALL. Am very sure about it, because when I execute the same statement in "isql" , it works perfectly.
    Can anyone, let me know whether Is it a limitation on Report Builder with Sybase db or Is any configuration do I miss??
    Also, let me know if there is any work around process to handle this situation.
    Sample Query I tried :
    select item, avg(rate) from inventory
    where item=:mitem /* mitem is a variable */
    group by item
    Any information is welcome.
    Thanks & Regards
    Anand
    Mail ID: [email protected]

    Hi Sachin,
    I too, got through the issue. Sorry am bit late in updating you. But still I would say it is not on consistent(my feedback as per I grabbed from the behavior. Say, I accepted the query in a particular order of WHERE clause, then If I change the order it will throw an error message saying "Incorrect syntax".)
    Anyway working fine. Thanks for your immediate response with useful hints.
    Rgds
    Anand
    Hi Anand,
    Yes, JDBCPDS accepts all Select queries which follows SQL Specification.
    It would be a valid query as per the database used.
    Please try again, Bind parameters can be placed in any or all of the conditions of SQL Query in JDBCPDS.
    I am able to use them in both the cases you told.
    With Regards
    Reports team

  • Error: The target database JDBC driver class cannot be loaded

    Hi
    We have a GTC DB connector deployed and configured in one environment. We are able to provision the users to DB table in that environment.
    Then we have taken export of all related data objects(like IT Resource, Resource Obj, Process Defs, Adapter tasks, etc) and imported to another environment.
    In this environment we changed the conn parameters in IT resource and made sure that all the files has been copied to respective folders under Xellerate.
    When ever we try to provision user to the DB it throws an error message as The target database JDBC driver class cannot be loaded as a response and the create user task is rejected.
    Database: MS SQL Server.
    App Server: WebSphere App Server 6.1
    OIM: 9.1.0.1
    Does any one faced this type of issue??
    Thanks

    Thanks lot for the quick response.
    I have copied the sqljdbc.jar file to the ThirdParty folder and restarted in App server. Now that the earlier error "The target database JDBC driver class cannot be loaded" is not appearing while provisioning in the rejected task.
    I am getting a new error "GCPROV.ProvTransportProvider.DBProvisioningTransport.DB_GET_CONNECTION_ERROR".
    Can you please let me know the reason for this. All the connections parameters are correct to connect to the target databse.
    Waiting for the response.

  • A sign Applet unable to load "oracle.jdbc.OracleDriver" class

    hi,
    i am chiranjit , i am now working in a web based ERP. where i am using a signed applet which unable to load "oracle.jdbc.OracleDriver" class but it easily loading "sun.jdbc.odbc.JdbcOdbcDriver", i am also giving my code:
    import java.sql.*;
    import java.math.*;
    import java.io.*;
    import java.awt.*;
    class JdbcTest extends Applet{
    public static void main (String args[]) throws SQLException {
    // Load Oracle driver
    DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
    // Connect to the local database
    Connection conn =
    DriverManager.getConnection
    ("jdbc:oracle:thin:@192.168.16.7:1521:kris",
    "plsql", "oracle");
    // Query the employee names
    Statement stmt = conn.createStatement ();
    ResultSet rset = stmt.executeQuery ("SELECT FIRST_NAME FROM
    AUTHORS");
    // Print the name out
    while (rset.next ())
    System.out.println (rset.getString (1));
    // Close the result set, statement, and the connection
    rset.close();
    stmt.close();
    conn.close();
    }

    Hint: The sun.jdbc.odbc.JdbcOdbcDriver is available in any JRE distribution. The Oracle driver is not.

  • JDBC query against Sybase through jConnect5.5 in Oracle 9i Reports Builder

    Hi There,
    I am trying to connect to Sybase using JDBC query using jConnect55 driver.
    I am not able to do so. I get an error:
    ERR 62002: Failed to connect to the datasource JZ0D5 JZ0D5: Error loading protocol com.sybase.jdbc2//255.255.255.255//255.255.255.255
    Driver entry in my jdbcpds.conf file is
    <driver name ="jConnect55"
    subProtocol ="sybase"
    connectString ="mainProtocol:subProtocol://databaseName"
    class = "com.sybase.jdbc2.jdbc.SybDriver"
    connection = "oracle.reports.plugin.datasource.jdbcpds.JDBCConnectionHandling" loginTimeout = "0">
    <property name="DatabaseName" value="tempdb"/>
    </driver>
    The entry I make in jdbc query connection dialog box is as under:
    User Name:test
    password:secret
    Databse: 255.255.255.255:9999/tempdb
    Driver Type: jConnect55
    Can you point me where I am wrong?
    Thanks in advance
    Ketan Patel

    Hi Sachin,
    I too, got through the issue. Sorry am bit late in updating you. But still I would say it is not on consistent(my feedback as per I grabbed from the behavior. Say, I accepted the query in a particular order of WHERE clause, then If I change the order it will throw an error message saying "Incorrect syntax".)
    Anyway working fine. Thanks for your immediate response with useful hints.
    Rgds
    Anand
    Hi Anand,
    Yes, JDBCPDS accepts all Select queries which follows SQL Specification.
    It would be a valid query as per the database used.
    Please try again, Bind parameters can be placed in any or all of the conditions of SQL Query in JDBCPDS.
    I am able to use them in both the cases you told.
    With Regards
    Reports team

  • JDBC Query using PL/SQL

    I have gotten this to work in my Reports class but can not get this to work at my company. Basically I'm trying to use the JDBC query in Report Builder.
    Here is my Ref Cursor Code:
    CREATE OR REPLACE PACKAGE SCOTT.types is
    type sqlcur is REF cursor;
    end;
    Here is my Pl/SQL function:
    CREATE OR REPLACE FUNCTION SCOTT.test return Scott.types.sqlcur is
    c1 Scott.types.sqlcur;
    begin
    open c1 for select * from scott.emp;
    return c1;
    end;
    I can get this to work in SQL Plus by doing the following:
    var r refcursor
    exec :r := test;
    print r When I go into Reports Builder->JDBC query I connect to the SCOTT db using tiger as the password. I type in the function name TEST and get the error "wrong number or types of arguments in call TEST". I have tried "call TEST" but that doesnt work either. If I use "call TEST" I get an error saying it expected characters ":=(@" etc....
    I know my connection works because I can do a "select * from emp" and get results. Can anyone get this to work?
    I'm running Report Builder 9.0.2.0.3
    I have done multiple searches on this issue and most responses point someone to links that dont work or documentation. I have read them and my code above should work but doesnt........Please put some real examples or code that works with the "Scott" schema.
    Thanks

    hi Shawn
    When running jdbc quesry based on SP with Oracle DB, the first parameter of the store procedure should be of ref cursor type and it shall be a OUT parameter.
    For example:
    CREATE OR REPLACE PACKAGE jdbcpdspkg AS
    TYPE Empcur IS ref cursor ;
    procedure proc_with_param      (p_emp_cv out jdbcpdspkg .empcur, p1 in number, p2 in number , p3 in number, p4 in number , p5 in number) ;
    Thanks
    Rohit

  • Inserting files in to Oracle 8i database through JDBC - Only 4k data file

    Hi,
    I need to insert a files(images or excel files, doc files etc..) in to oracle 8i database through JDBC program. But i am not able to store more than 4k data files in to files. can any body give me solutions regarding this.
    My code is like this...
    String fileName ="Sample.jpg";
                                  String dataSource = "jdbc/oracle";
                   File file=null;
                   FileInputStream fis = null;
                   Context initCtx=null;
                   DataSource ds = null;
                   Connection con = null;
                   try
                        initCtx = new InitialContext();
                        ds = (DataSource)initCtx.lookup(dataSource);
                        con = ds.getConnection();
                      try
                         file = new File(fileName);
                         fis = new FileInputStream(file);
                        catch(FileNotFoundException fe)
                             out.println("File Not Found");
                                            PreparedStatement pstmt = con.prepareStatement("insert into bfiles values(?,?)");
                        pstmt.setString(1, fileName);
                        pstmt.setBinaryStream(2, fis, (int)file.length());
                        pstmt.executeUpdate();
                        out.println("Inserted");
                        fis.close();
                        pstmt.close();
                        con.close();
                        out.println("closed");
                   catch(Exception e)
                        out.println(e);
               }     in Oracle bi i have created a table like this :
    CREATE TABLE BFILES
      FILENAME     VARCHAR2(100)                    DEFAULT NULL,
      FILECONTENT  BLOB                             DEFAULT EMPTY_BLOB()
    )Please help me ourt to solve this problem.
    i got struck in this problem.
    its urgent
    thanks in advance
    djshivu

    Hi Shanu.
    Thanks for your help...
    By Using THIN driver also we can insert any files more than 4k and and retrive same. Fallowing codes worked fine for me using thin Driver .
    Following are the 2 programs to write and read.
    we can insert and retrieve any format of files ( jpg, gif, doc, xsl, exe, etc...)
    =======================================================
    // Program to insert files in to table
    import oracle.jdbc.driver.*;
    import oracle.sql.*;
    import java.sql.*;
    import java.io.*;
    import java.awt.image.*;
    import java.awt.*;
    * @author  Shivakumar D.J
    * @version
    public class WriteBlob{
    public static void main(String[] args){
    String filename = "018-Annexure-A.xls";
    Connection conn = null;
    try{
        Class.forName("oracle.jdbc.driver.OracleDriver");
        conn=DriverManager.getConnection("jdbc:oracle:thin:@test:1521:orcl","modelytics","modelytics");
        conn.setAutoCommit(false);
        Statement st = conn.createStatement();
        int b= st.executeUpdate("insert into bfiles values('"+filename+"', empty_blob())");
        ResultSet rs= st.executeQuery("select * from bfiles for update");
        rs.next();
        BLOB blob=((oracle.jdbc.driver.OracleResultSet)rs).getBLOB(2);
        FileInputStream instream = new FileInputStream(filename);
        OutputStream outstream = blob.getBinaryOutputStream();
        int chunk = blob.getChunkSize();
        byte[] buff = new byte[chunk];
        int le;
        while( (le=instream.read(buff)) !=-1)
            outstream.write(buff,0,le);
        instream.close();
        outstream.close();
        conn.commit();
        conn.close();
        conn = null;
        System.out.println("Inserted.....");
       catch(Exception e){
            System.out.println("exception"+e.getMessage());
            e.printStackTrace();
       }//catch
    }=======================
    // Program to retrieve files from database
    [import java.sql.*;
    import java.io.*;
    import java.awt.*;
    public class ReadImage
    public static void main(String a[])
        String fileName ="018-Annexure-A.xls";
        try
              Driver driver = new oracle.jdbc.driver.OracleDriver();
              DriverManager.registerDriver(driver);
              Connection con = DriverManager.getConnection("jdbc:oracle:thin:@test:1521:orcl", "modelytics", "modelytics");
            File file = new File("C:/Documents and Settings/USERID/Desktop/dump.xls");
              FileOutputStream targetFile=  new FileOutputStream(file); // define the output stream
              PreparedStatement pstmt = con.prepareStatement("select filecontent from bfiles where filename= ?");
              pstmt.setString(1, fileName);
               ResultSet rs = pstmt.executeQuery();
               rs.next();
               InputStream is = rs.getBinaryStream(1);
              byte[] buff = new byte[1024];
               int i = 0;
               while ((i = is.read(buff)) != -1) {
                    targetFile.write(buff, 0, i);
                   System.out.println("Completed...");
            is.close();
            targetFile.close();
            pstmt.close();
           con.close();
        catch(Exception e)
              System.out.println(e);
    }====================
    Table Structure is like this
    CREATE TABLE BFILES
      FILENAME     VARCHAR2(100)                    DEFAULT NULL,
      FILECONTENT  BLOB                             DEFAULT EMPTY_BLOB()
    )========================================================
    i hope above codes will helpful for our future programmers
    thanks shanu...
    regards
    djshivu...(javashivu)

  • Not able to connect to database using jdbc

    Respected sir/madam,
    I am new to java and i am trying to connect to database which is necessary for me in project when i wrote the code using class.forName i am able to compile but when runnig i am getting two exceptionns one is oracle.jdbc.driver.oracledriver not found or excetion in thread main class not found please help me

    Subash,
    1) Please refrain from cross-posting (posting the same message into two or more forums). This question was better asked in the JDBC forum as you eventually put it but you already posted here so if that happens again next time just leave the original thread be.
    2) Your compilation classpath and your runtime classpath are not related. As a matter of fact with well written JDBC code and under most conditions you should not need your driver in your compilation classpath at all, only your runtime one.
    3) Your driver is not in your runtime classpath. That is the error that you need to resolve.

  • Jdbc query cached?  OR how do I get current results?

    Two CF pages exist: a "list" page and an "edit" page.  The user selects a record from the "list" page via a link to the "edit" page.  The "edit" page is a form which submits back to itself to update the record, then returns to the "list" page via cflocation.
    There are literally hundreds of mdb files which could be accessed via these pages, based on the user login information.  The path to the files is known by their login, and we don't want to maintain hundreds of odbc connections, so the jdbc driver within cfscript is being used to access the data, with the path to the database file reference in the getConnection function.
    The problem is this:  after the record is updated and cflocation returns to the list page, the list page does not return the current database information (the record which was just edited still shows the old information).  If the page is refreshed manually (F5 type stuff), then the updated data is shown.  It's like the query on the "list" page is being cached or something.  I have tried a meta tag to expire the page, but that doesn't help.
    Another set of data is edited on these pages but resides on SQL Server and used cfquery.  This problem does not exist with that set of code.
    CF MX7 is the CF Server version.
    Here's the cfscript used on the "list" page:
    <cfscript>
      classLoader = createObject("java", "java.lang.Class");
      classLoader.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      dm = createObject("java","java.sql.DriverManager");
      con = dm.getConnection("jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};Dbq=#fullPathToMDBFile#;Uid=;Pwd=;");
      st = con.createStatement();
      rs = st.ExecuteQuery( "#GroupQuery#" );
      group = createObject("java", "coldfusion.sql.QueryTable").init(rs);
    </cfscript>
    And the cfscript on the "edit" page:
       <cfscript>
        classLoader = createObject("java", "java.lang.Class");
        classLoader.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        dm = createObject("java","java.sql.DriverManager");
        con = dm.getConnection("jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};Dbq=#fullPathToMDBFile#;Uid=;Pwd=;");
        st = con.createStatement();
        st.Execute( "#UpdateQuery#" );
       </cfscript>
    Which is followed by:
         <cflocation url="listrecs.cfm">
    At the suggestion of a java-knowledgeable friend, I tried:
      st.close();
      con.close();
    after the st.ExecuteQuery, but still got the same results.
    Thoughts??
    Thanks.

    Yes, always do that anyway. It is not good to have open connections lying around.
    Are you sure it is not just a persistent case of browser caching? Try the old trick of tacking a random number onto the url each time, using randRange().  See if it makes a difference.
    As far as datasources, you could try creating a single datasource and using it to query all the other databases.  IIRC it should be listed under external tables in the MS Access help files.  I can never remember the syntax, but is something like:
    SELECT  Columns
    FROM     TableA IN 'c:\databaseFolder\someDatabaseName.mdb'
    IIRC MS Access databases let you query another databases using a special syntax fro
    [b]Update:[/b] Disclaimer, I have not used Access in years.  So I have no idea about the potential issues, other than the obvious (ie Access is not really designed for this)
    At the suggestion of a java-knowledgeable friend, I tried:
      st.close();
      con.close();
    after the st.ExecuteQuery, but still got the same results.

  • JDBC driver - Class oracle.jdbc.driver.OracleDriver not found.

    Greetings:
    When I tried to compile an test script (as attached below) to test the driver, I always ended up with the following error message:
    ....java:17: Class oracle.jdbc.driver.OracleDriver not found.
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    Could somebody shine some light on it? I would very much appreciate it.
    By the way, I have an Oracle DBMS (8.1.7) with jre1.1.7. My Java is jdk1.2 and the driver is ocijdbc8.dll
    Wil
    *************** The test script *************
    import java.sql.*;
    class Users
    public static void main (String args [])
    throws SQLException, ClassNotFoundException
    // Load the Oracle JDBC driver
    Class.forName ("oracle.jdbc.driver.OracleDriver");
    // Connect to the database
    // You can put a database name after the @ sign in the connection URL.
    Connection conn =
    DriverManager.getConnection ("jdbc:oracle:oci8:@US10", "QM24202E", "QM24202E");
    // Create a Statement
    Statement stmt = conn.createStatement ();
    // Select ... table
    ResultSet rset = stmt.executeQuery ("select USERID from USERS");
    // Iterate through the result and print the ... names
    while (rset.next ())
    System.out.println (rset.getString (1));

    check out what thomas Fly wrote on another discussion forum about connection with JDBC, i tried it and i haven't gotten it
    to work yet but at least i don't have the "... not found" error,
    you should try it too, and i think it's good to tell you that i
    still haven't installed the oracle client on my windows Me PC.
    Hope this help you
    This may help also... I have Oracle installed on a Linux PC at 192.168.1.4 on my LAN, listening on port 1521. I can connect from another PC (Linux / Windows ME dual boot, though running Windows at the time of this experiment) using the following program:
    import java.sql.*;
    public class sqlLookup {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
    String dbUrl = "jdbc:oracle:thin:@192.168.1.4:1521:ORA8";
    String user = "thomasfly";
    String password = "maverick";
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    Connection c = DriverManager.getConnection(dbUrl, user, password);
    Statement s = c.createStatement();
    // SQL code:
    ResultSet r = s.executeQuery("select * from members");
    while(r.next()) {
    // Capitalization doesn't matter:
    System.out.println(r.getString("Name") + ", " + r.getString("id") + ": " + r.getString("email") );
    s.close(); // Also closes ResultSet
    I downloaded classes12.zip for Oracle 8.1.7 and put it into the C:\Windows directory, and mounted C:\Windows\classes12.zip in Forte for Java (equivalent to adding it to the classpath if I were running the program from a DOS window, rather than in Forte).
    ORA8... capitalization may be important... is the name of my database, which may be found in the tnsnames.ora file in $ORACLE_HOME/resources.
    The query gets the Name, id, and email fields from the table "members" in the database.
    This is just a barebones program, and each time it's run, the Oracle listener has to be stopped and restarted before the program can be successfully run again.

  • Error Connecting to database URL jdbc:oracle:oci:@rmsdbtst as user rms13 java.lang.Exception:UnsatisfiedLinkError encountered when using the Oracle driver

    Trying to Install RMS application 13.2.2 and I get past the pre-installation checks and when I get to the Data Source details and enter the data source details with the check box checked to validate the schema/Test Data Source I get the following error:
    Error Connecting to database URL jdbc:oracle:oci:@rmsdbtst as user rms13 java.lang.Exception:UnsatisfiedLinkError encountered when using the Oracle driver. Please check that the library path is set up properly or switch to the JDBC thin client oracle/jdbc/driver/T2CConnection.getLibraryVersioNumber()
    Checks performed:
    RMS Application code location and directory contents:
    [oracle@test-rms-app application]$ pwd
    /binary_files/STAGING_DIR/rms/application
    [oracle@test-rms-app application]$ ls -ltr
    total 144
    -rw-r--r-- 1 oracle oinstall   272 Dec 7  2010 version.properties
    -rw-r--r-- 1 oracle oinstall   405 Jan 16 2011 expected-object-counts.properties
    -rw-r--r-- 1 oracle oinstall   892 May 13 2011 ant.install.properties.sample
    -rw-r--r-- 1 oracle oinstall 64004 Jun  6  2011 build.xml
    drwxr-xr-x 9 oracle oinstall  4096 Jun 16 2011 rms13
    drwxr-xr-x 3 oracle oinstall  4096 Jun 16 2011 installer-resources
    drwxr-xr-x 3 oracle oinstall  4096 Jun 16 2011 antinstall
    drwxr-xr-x 2 oracle oinstall  4096 Jun 16 2011 ant-ext
    drwxr-xr-x 5 oracle oinstall  4096 Jun 16 2011 ant
    -rw-r--r-- 1 oracle oinstall 11324 Dec 18 09:18 antinstall-config.xml.ORIG
    -rwxr-xr-x 1 oracle oinstall  4249 Dec 18 10:01 install.sh
    drwxr-xr-x 4 oracle oinstall  4096 Dec 18 10:06 common
    -rw-r--r-- 1 oracle oinstall 16244 Dec 19 10:37 antinstall-config.xml
    -rw-r--r-- 1 oracle oinstall   689 Dec 19 10:37 ant.install.log
    [oracle@test-rms-app application]$
    Application installation:
    [oracle@test-rms-app application]$ ./install.sh
    THIS IS the driver directory
    Verified $ORACLE_SID.
    Verified SQL*Plus exists.
    Verified write permissions.
    Verified formsweb.cfg read permissions.
    Verified Registry.dat read permissions.
    Verified Java version 1.4.2.x or greater. Java version - 1.6.0
    Verified Tk2Motif.rgb settings.
    Verified frmcmp_batch.sh status.
    WARNING: Oracle Enterprise Linux not detected.  Some components may not install properly.
    Verified $DISPLAY - 172.16.129.82:0.0.
    This installer will ask for your "My Oracle Support" credentials.
    Preparing installer. This may take a few moments.
    Your internet connection type is: NONE
    Integrating My Oracle Support into the product installer workflow...
         [move] Moving 1 file to /binary_files/STAGING_DIR/rms/application
    Installer preparation complete.
    MW_HOME=/u01/app/oracle/Middleware/NewMiddleware1034
    ORACLE_HOME=/u01/app/oracle/Middleware/NewMiddleware1034/as_1
    ORACLE_INSTANCE=/u01/app/oracle/Middleware/NewMiddleware1034/asinst_1
    DOMAIN_HOME=/u01/app/oracle/Middleware/NewMiddleware1034/user_projects/domains/rmsClassDomain
    WLS_INSTANCE=WLS_FORMS
    ORACLE_SID=rmsdbtst
    JAVA_HOME=/u01/app/oracle/jrockit-jdk1.6.0_45-R28.2.7-4.1.0
    Launching installer...
    To make sure I have connectivity from the app server to the database (on a database server) here are the steps followed:
    [oracle@test-rms-app application]$ tnsping rmsdbtst
    TNS Ping Utility for Linux: Version 11.1.0.7.0 - Production on 19-DEC-2013 10:41:40
    Copyright (c) 1997, 2008, Oracle.  All rights reserved.
    Used parameter files:
    Used TNSNAMES adapter to resolve the alias
    Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = test-rms-db.vonmaur.vmc)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SID = rmsdbtst)))
    OK (0 msec)
    [oracle@test-rms-app application]$
    [oracle@test-rms-app application]$ sqlplus rms13@rmsdbtst
    SQL*Plus: Release 11.1.0.7.0 - Production on Thu Dec 19 10:46:18 2013
    Copyright (c) 1982, 2008, Oracle.  All rights reserved.
    Enter password:
    Connected to:
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    SQL> exit
    Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    [oracle@test-rms-app application]$
    [oracle@test-rms-app application]$ ping test-rms-db
    PING test-rms-db.vonmaur.vmc (192.168.1.140) 56(84) bytes of data.
    64 bytes from test-rms-db.vonmaur.vmc (192.168.1.140): icmp_seq=1 ttl=64 time=0.599 ms
    64 bytes from test-rms-db.vonmaur.vmc (192.168.1.140): icmp_seq=2 ttl=64 time=0.168 ms
    64 bytes from test-rms-db.vonmaur.vmc (192.168.1.140): icmp_seq=3 ttl=64 time=0.132 ms
    64 bytes from test-rms-db.vonmaur.vmc (192.168.1.140): icmp_seq=4 ttl=64 time=0.158 ms
    64 bytes from test-rms-db.vonmaur.vmc (192.168.1.140): icmp_seq=5 ttl=64 time=0.135 ms
    --- test-rms-db.vonmaur.vmc ping statistics ---
    5 packets transmitted, 5 received, 0% packet loss, time 4001ms
    rtt min/avg/max/mdev = 0.132/0.238/0.599/0.181 ms
    [oracle@test-rms-app application]$
    [oracle@test-rms-app application]$ uname -a
    Linux test-rms-app.vonmaur.vmc 2.6.18-128.el5 #1 SMP Wed Jan 21 08:45:05 EST 2009 x86_64 x86_64 x86_64 GNU/Linux
    [oracle@test-rms-app application]$
    [oracle@test-rms-app application]$ cat /etc/*-release
    Enterprise Linux Enterprise Linux Server release 5.3 (Carthage)
    Red Hat Enterprise Linux Server release 5.3 (Tikanga)
    [oracle@test-rms-app application]$
    The database is created and all the batch file scripts have been successfully deployed.  Now working on the application server.  The  Weblogic server is installed and 11g forms and reports are installed successfully.
    Any help would be helpful.
    Thanks,
    Ram.

    Please check MOS Notes:
    FAQ: RWMS 13.2 Installation and Configuration (Doc ID 1307639.1)

  • How can I access the oracle/sql server jdbc driver class files from my cust

    I have a war file in which I have custom DataSource i.e mypackage.Datasource class. Its basically the need of my application. In this class we connect to datasource and link some of our programming artifacts .
    I have deployed the oracle jdbc driver and deploy my application as ear with datasources.xml in the meta inf file. Inspite of that my code fails to load the jdbc driver classes.
    Here is the extract of the code :
            Class.forName("oracle.jdbc.OracleDriver").newInstance();
             String url = "jdbc:oracle:thin:@dataserver:1521:orcl";
            Connection conn = DriverManager.getConnection(url, "weblims3", "labware");
            if(conn != null){
              out.println("the connection to the database have been achieved");
            out.println("conn object achived= " + conn);
    Class.forname fails in this case. I can see the ojdbc5.jar the driver jar in usr\sap\CE1\J00\j2ee\cluster\bin\ext\ojdbc5  . I even put the ojdbc.jar in web-inf/lib and application lib but does not help at all. Hope I have explained my problem clearly.
    I deployed the jdbc driver in the name of ojdbc5 .
    I am stuck here. It will be great help if anyone can help me in this. Thanks in advance.

    Bent,
    You can access the database from your Java portlet, just like from any other Java/JSP environment. Yes, you can use JDBC, as well as BC4J.
    The Discussion Forum portlet was built using BC4J, take a look at it's source to see how it was done.
    Also, check out Re: BC4J Java portlet anyone?, it contains a lot of useful information too.
    Peter

Maybe you are looking for