简体   繁体   English

Java Web应用程序中的Oracle 10g数据库集成

[英]Oracle 10g database integration in a java web application

I'm building a program in java that runs through a Jboss 5.0.1 application server. 我正在用Java构建通过Jboss 5.0.1应用服务器运行的程序。 The program has to consult and update tables in an Oracle 10g database but I'm having a lot of trouble with it. 该程序必须查询和更新Oracle 10g数据库中的表,但是我遇到了很多麻烦。

Basically, i have a class called DAO that connects whith the database and makes a simple query through the method "prueba()". 基本上,我有一个称为DAO的类,该类连接数据库并通过“ prueba()”方法进行简单查询。 Here's the implementation of the class: 这是该类的实现:

package dao;

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Properties;

import valueObject.ItemFisico;



public class DAO {

//----------------------------------------------------
//Constantes
//----------------------------------------------------
/**
 * ruta donde se encuentra el archivo de conexion.
 */
public final static String ARCHIVO_PROPIEDADES = "./data/conexion.properties";

//----------------------------------------------------
//Atributos
//----------------------------------------------------
/**
 * conexion con la base de datos
 */
public Connection conexion;

/**
 * nombre del usuario para conectarse a la base de datos.
 */
private String usuario;

/**
 * clave de conexion a la base de datos.
 */
private String clave;

/**
 * URL al cual se debe conectar para acceder a la base de datos.
 */
private String cadenaConexion;

/**
 * constructor de la clase. No inicializa ningun atributo.
 */
public DAO() 
{       

}

// -------------------------------------------------
// Metodos
// -------------------------------------------------

/**
 * obtiene ls datos necesarios para establecer una conexion
 * Los datos se obtienen a partir de un archivo properties.
 */
public void inicializar()
{
    try
    {
        File arch= new File(ARCHIVO_PROPIEDADES);
        Properties prop = new Properties();
        FileInputStream in = new FileInputStream( arch );

        prop.load( in );
        in.close( );

        cadenaConexion = prop.getProperty("url");   
        usuario = prop.getProperty("usuario");  
        clave = prop.getProperty("clave");  
        final String driver = prop.getProperty("driver");
        Class.forName(driver);

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

/**
 * Metodo que se encarga de crear la conexion con el Driver Manager
 * a partir de los parametros recibidos.
 * @param url direccion url de la base de datos a la cual se desea conectar
 * @param usuario nombre del usuario que se va a conectar a la base de datos
 * @param clave clave de acceso a la base de datos
 * @throws SQLException si ocurre un error generando la conexion con la base de datos.
 */
private void establecerConexion(String url, String usuario, String clave) throws SQLException
{
    try
    {
        conexion = DriverManager.getConnection(url,usuario,clave);
    }
    catch( SQLException exception )
    {
        throw new SQLException( "ERROR: ConsultaDAO obteniendo una conexion." );
    }
}

/**
 *Cierra la conexion activa a la base de datos. Ademas, con=null.
 * @param con objeto de conexion a la base de datos
 * @throws SistemaCinesException Si se presentan errores de conexion
 */
public void closeConnection(Connection connection) throws Exception {        
    try {
        connection.close();
        connection = null;
    } catch (SQLException exception) {
        throw new Exception("ERROR: ConsultaDAO: closeConnection() = cerrando una conexion.");
    }
} 

// ---------------------------------------------------
// Metodos asociados a los casos de uso: Consulta
// ---------------------------------------------------  

public void prueba() throws Exception{
    String prueba = "SELECT * FROM PARRANDEROS.BARES b where b.presupuesto='Bajo' ";


    PreparedStatement st=null;

    try{
        inicializar();
        establecerConexion(cadenaConexion, usuario, clave);
        st = conexion.prepareStatement(prueba);

        ResultSet r= st.executeQuery(prueba);
        while(r.next()){
            System.out.println(r.getInt("ID")+":"+r.getString("NOMBRE")+":"+r.getString("CIUDAD")+":"+r.getString("PRESUPUESTO")+":"+r.getString("CANT_SEDES"));

        }

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

    }

    finally{
        if (st != null) 
        {
            try {
                st.close();
            } catch (SQLException exception) {

                throw new Exception("ERROR: ConsultaDAO: loadRow() =  cerrando una conexi�n.");
            }
        }
        closeConnection(conexion);
    }

}


}

Here's the thing, everything in this class works fine, i have run it as a Java application through a simple main() method and it performs the query just fine. 事情是这样,此类中的所有内容都可以正常工作,我已经通过一个简单的main()方法将其作为Java应用程序运行,并且它可以很好地执行查询。 The driver .jar is well placed and referenced and all properties used for the connection are fine. 驱动程序.jar放置正确并且被引用,并且用于连接的所有属性都很好。

Now, when I run the whole application (including other classes like servlets and so) mounted on the running server, and then try to run again the method "prueba()", it crashes. 现在,当我运行正在运行的服务器上安装的整个应用程序(包括servlet等其他类),然后尝试再次运行方法“ prueba()”时,它崩溃了。 It gets a FileNotFoundException caused by the conexion.properties file, which exists!!!. 它获取由conexion.properties文件引起的FileNotFoundException,该文件存在!!!

I am not really an expert on web applications and don't really know if i have to make any changes on the server configuration or in another place. 我实际上不是Web应用程序方面的专家,也不真正知道我是否必须对服务器配置或其他位置进行任何更改。 Can someone help me? 有人能帮我吗?

The problem is that you are using absolute path ./data/conexion.properties which is fine when you run the program locally. 问题是您使用的是绝对路径./data/conexion.properties ,这在本地运行程序时很好。 But deploying to an application server, would make the path invalid because the file will be in some other location (eg /apps/jboss/.../myapp/data/conexion.properties ). 但是部署到应用程序服务器将使路径无效,因为该文件将位于其他位置(例如/apps/jboss/.../myapp/data/conexion.properties )。 In the inicializar method replace the following inicializar方法中,替换以下内容

File arch= new File(ARCHIVO_PROPIEDADES);

with

URL url = getClass().getClassLoader().getResource("conexion.properties");
File arch= new File(url.getFile());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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