CodeCharge Studio
search Register Login  

Visual PHP Web Development

Visually Create Internationalized Web Applications, Web Reports, Calendars, and more.
CodeCharge.com

YesSoftware Forums -> CodeCharge Studio -> Java

 transactional control - JDBC

Print topic Send  topic

Author Message
saamondino

Posts: 33
Posted: 05/19/2009, 11:10 AM


In the buton of my Form, Envents->Server->On Click-Custom Code, I wrote the following code:

String pasos = "0<br>";
int retorno = 0;

//--- Open Connection ----
JDBCConnection conn = JDBCConnectionFactory.getJDBCConnection("ConPRUEBAS");
String sql = "";
String id_cabexp = Utils.convertToString(e.getPage().getRecord("VARIOS").getControl("ID_CAB_EXP").getFormattedValue());

//----- Borro el DET_REG_EXP -------
sql = "DELETE FROM TRB_DET_INF WHERE TRB_CAB_EXP_ID = '" + id_cabexp + "'";
pasos += " 1d " + sql + "<br>";
retorno = conn.executeUpdate(sql);
if (retorno <= 0) {
Utils.printFatalError(" -->> Error !!! = " + pasos, e.getPage().getResponse());
}
//----- FIN Borro el DET_REG_EXP -------

//--- Borro TRB_VEHICULO ---
sql = "DELETE FROM TRB_VEHICULO WHERE TRB_CAB_EXP_ID = '" + id_cabexp + "'";
pasos += " 2d " + sql + "<br>";
retorno = conn.executeUpdate(sql);
if (retorno <= 0) {
Utils.printFatalError(" -->> Error !!! = " + pasos, e.getPage().getResponse());
}
//--- FIN Borro TRB_VEHICULO ---


//----- Borro el TRB_PASOS -------
sql = "DELETE FROM TRB_PASOS WHERE ID_CAB_EXP_1_2 = '" + id_cabexp + "'";
pasos += " 7d " + sql + "<br>";
retorno = conn.executeUpdate(sql);
if (retorno <= 0) {
Utils.printFatalError(" -->> Error !!! = " + pasos, e.getPage().getResponse());
}
//--- FIN Borro TRB_PASOS ---

...

// INSERT, UPDATE, .....

...

// --- CLose Connection ---
conn.closeConnection();


This Works well.


Now, I need to modify the code, adding a transactional control. If one of the transactions flaw that executes a rollback.

The data base that I am using, is Oracle 10G. The JDBC, is Download the Oracle Oficial Site, I read that should use the Method

conn.setAutoCommit(false);

to disable autocommit and

conn.setAutoCommit(true);

to active autocommit, by default is conn.setAutoCommit(true);

but..., this Method NO EXIST in the class JDBCConnection.



Then, I wrote this code:

DBConnectionManager DBM;
Connection conn = null;

Statement stmt = null;
ResultSet rs = null;

try {
DBM = DBConnectionManager.getInstance();
conn = DBM.getConnection("ConPRUEBAS");

stmt = conn.createStatement();
conn.setAutoCommit(false);
String sql = "";
String id_cabexp = Utils.convertToString(e.getPage().getRecord("VARIOS").getControl("ID_CAB_EXP").getFormattedValue());

//----- Borro el DET_REG_EXP -------
sql = "DELETE FROM TRB_DET_INF WHERE TRB_CAB_EXP_ID = '" + id_cabexp + "'";
pasos += " 1d " + sql + "<br>";
retorno = conn.executeUpdate(sql);
if (retorno <= 0) {
Utils.printFatalError(" -->> Error !!! = " + pasos, e.getPage().getResponse());
}
//----- FIN Borro el DET_REG_EXP -------

//--- Borro TRB_VEHICULO ---
sql = "DELETE FROM TRB_VEHICULO WHERE TRB_CAB_EXP_ID = '" + id_cabexp + "'";
pasos += " 2d " + sql + "<br>";
retorno = conn.executeUpdate(sql);
if (retorno <= 0) {
Utils.printFatalError(" -->> Error !!! = " + pasos, e.getPage().getResponse());
}
//--- FIN Borro TRB_VEHICULO ---


//----- Borro el TRB_PASOS -------
sql = "DELETE FROM TRB_PASOS WHERE ID_CAB_EXP_1_2 = '" + id_cabexp + "'";
pasos += " 7d " + sql + "<br>";
retorno = conn.executeUpdate(sql);
if (retorno <= 0) {
Utils.printFatalError(" -->> Error !!! = " + pasos, e.getPage().getResponse());
}
//--- FIN Borro TRB_PASOS ---

...

// INSERT, UPDATE, .....

...


conn.commit();
conn.close();
e.getPage().setRedirectString( "TRB_CAB_EXP_list.jsp" );

} catch (Exception ex) {
try {
if (conn != null) {
conn.rollback();
}
Utils.printFatalError("Database error: " + ex.getMessage() + " -> " + pasos, e.getPage().getResponse());
} catch (Exception ex2) {
Utils.printFatalError("Database error: " + ex2.getMessage() + " -> " + pasos, e.getPage().getResponse());
}
} finally {
try {
if (rs != null) {
rs = null;
}
if (stmt != null) {
stmt = null;
}
if (conn != null) {
if (conn.isClosed() == false) {
conn.close();
}
conn = null;
}
} catch (Exception ex) {
Utils.printFatalError("Database error: " + ex.getMessage() + " -> " + pasos, e.getPage().getResponse());
}
}

and... include in JSP File <%@page import="com.codecharge.*,...,...util.cache.ICache,java.util.regex.*,java.sql.*,java.sql.DriverManager,java.sql.Connection,java.sql.SQLException"%>


This Work Fine,

But... I have this problem, After pressing 5 times the button, gives me this error:


Estado HTTP 500 -

type Informe de Excepción

mensaje

descripción El servidor encontró un error interno () que hizo que no pudiera rellenar este requerimiento.

excepción

org.apache.jasper.JasperException: Unable to create connection 'ConPRUEBAS' to the database.
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:476)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:389)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:315)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

causa raíz

java.lang.RuntimeException: Unable to create connection 'ConPRUEBAS' to the database.
com.codecharge.db.PoolJDBCConnection.getConnection(PoolJDBCConnection.java:23)
com.codecharge.db.JDBCConnection.<init>(JDBCConnection.java:85)
com.codecharge.db.PoolJDBCConnection.<init>(PoolJDBCConnection.java:15)
com.codecharge.db.JDBCConnectionFactory.getJDBCConnection(JDBCConnectionFactory.java:36)
com.codecharge.db.JDBCConnectionFactory.getJDBCConnection(JDBCConnectionFactory.java:27)
com.codecharge.ListProcessor.process(ListProcessor.java:39)
com.codecharge.RecordProcessor.processList(RecordProcessor.java:125)
com.codecharge.RecordProcessor.process(RecordProcessor.java:113)
com.codecharge.PageProcessor.process(PageProcessor.java:30)
com.codecharge.PageController.process(PageController.java:184)
org.apache.jsp.modules.inftrans.TRB_005fCAB_005fEXP_005flist_jsp._jspService(TRB_005fCAB_005fEXP_005flist_jsp.java:317)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:328)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:315)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

nota La traza completa de la causa de este error se encuentra en los archivos de diario de Apache Tomcat/5.5.23.



curiosity :
In the Proyect, if I Modify Connection Server "ConPRUEBAS"- Edit connection -->Server, Max. number of connection is 5.

- I think that it is out the connections Pool, are there connections that don't close, but like I verify this?

Somebody, can Help me please?

Best Regards.

Sergio.

PD: I Use, Codecharge Studio 3.2.0.6, Oracle 10G, Java 1.6, Apache Tomcat 5.5.23 and O.S. Windows 2003 Server.
View profile  Send private message
matheus

Posts: 386
Posted: 06/03/2009, 2:02 PM

To resolve this, you need change JDBCConnection.java.

Add this code in JDBCConnection.java

  
	public Connection getConn(){  
	   return conn;  
	}  

With, this you can do transaction operations in a Record (not in EditableGrid, because EditableGrid use one connection per line).

In Record you need create to Custom Code:
In BeforeBuildInsert or BeforeBuildUpdate or BeforeBuildDelete put this:

  
    try {   
        ((JDBCConnection)e.getCommand().getJDBCConnection()).getConn().setAutoCommit(false);  
    }catch(java.sql.SQLException sql_ex){}  

This you need close connection in AfterExecuteInsert or AfterExecuteUpdate or AfterExecuteDelete, with this:

  
    java.sql.Connection c = e.getCommand().getJDBCConnection().getConn();  
    try {  
        if ( !c.getAutoCommit()) {  
            if (e.getCommand().getJDBCConnection().hasErrors()){   
                try{ c.rollback(); }catch(Exception ex){ }  
            }else{ c.commit(); }  
        }  
    }catch(java.sql.SQLException sql_ex){ }  

_________________
Matheus Trevizan

Dynamix Software Ltda.
Blumenau SC Brasil
www.dynamix.com.br
View profile  Send private message
saamondino

Posts: 33
Posted: 06/04/2009, 9:20 AM

Hi matheus:

Thank you to answer.

You Solution is very Simple.

I solved this in way but complex.

But, I Need their opinion, perhaps my solution, consummates a lot of resource by memory.

I have created the following class java GetValuesConnection.java:
  
package com.codecharge;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletResponse;  
import com.codecharge.*;  
import com.codecharge.components.*;  
import com.codecharge.util.*;  
import com.codecharge.events.*;  
import com.codecharge.db.*;  
import com.codecharge.validation.*;  
import java.util.*;  
import java.io.*;  
import com.codecharge.util.cache.CacheEvent;  
import com.codecharge.util.cache.ICache;  
public class GetValuesConnection extends HttpServlet {  
    private String driverName;  
    private String urlName;  
    private String userName;  
    private String passwordName;  
  
	public void setUser(String userNamex) {  
          this.userName = userNamex;  
    }  
  
	public void setPassword(String passwordNamex) {  
          this.passwordName = passwordNamex;  
    }  
  
	public void setUrl(String urlNamex) {  
          this.urlName = urlNamex;  
    }  
  
	public void setDriver(String driverNamex) {  
          this.driverName = driverNamex;  
    }  
  
    public String getUser() {  
         return userName;  
    }  
  
    public String getPassword() {  
         return passwordName;  
    }  
  
    public String getDriver() {  
         return driverName;  
    }  
  
    public String getUrl() {  
         return urlName;  
    }  
  
    public boolean getvaluesConnName(String sNameConnection){  
	// Este es un Método retorna los valores url, driver, user, password para el Nombre de conexion pasado del Archivo site.properties  
		// Usar:  
		// GetValuesConnection valConn = new GetValuesConnection();  
		// boolean retorno= valConn.getvaluesConnName("ConPRUEBAS");  
		// Resultado:  
		// El retorno es true o false :   
	// si true devuelve valores si no son todos vacios  
	// valConn.getUrl;  
	// valConn.getUser;  
	// valConn.getPassword();  
	// valConn.getDriver();  
	boolean lRet = false;  
	String name_conn = sNameConnection;  
	int long_name_conn = name_conn.length();  
	String name_user = name_conn + ".user=";  
	String name_password = name_conn + ".password=";  
	String name_driver = name_conn + ".driver=";  
	String name_url = name_conn + ".url=";  
	String cFile = "/WEB-INF/site.properties";  
	String rpath = ContextStorage.getContext().getRealPath(cFile);  
	File f = new File( rpath );  
	String s = new String();  
	try {  
		BufferedReader bufferedReader = new BufferedReader(new FileReader( f ));  
		String line;  
		String saco_parte = "";  
		String saco_user = "";  
		String saco_password = "";  
		String saco_driver = "";  
		String saco_url = "";  
		while ((line = bufferedReader.readLine()) != null) {  
			if (line.length() >= long_name_conn){  
				saco_parte = line.substring(0, long_name_conn);  
				//***********  
				// Saco user  
				//***********  
				if (line.length() >= name_user.length() ){  
					saco_user = line.substring(0, name_user.length()); //saco_parte + ".user=";  
					if ( name_user.equals(saco_user) ){  
						this.setUser(line.substring(name_user.length()));  
					}  
				}  
				//***************  
				// Saco password  
				//***************  
				if (line.length() >= name_password.length() ){  
					saco_password = line.substring(0, name_password.length());  
					if ( name_password.equals(saco_password) ){  
						this.setPassword(line.substring(name_password.length()));  
					}  
				}  
				//*************  
				// Saco driver  
				//*************  
				if (line.length() >= name_driver.length() ){  
					saco_driver = line.substring(0, name_driver.length());  
					if ( name_driver.equals(saco_driver) ){  
						this.setDriver(line.substring(name_driver.length()));  
					}  
				}  
				//**********  
				// Saco url  
				//**********  
				if (line.length() >= name_url.length() ){  
					saco_url = line.substring(0, name_url.length());  
					if ( name_url.equals(saco_url) ){  
						this.setUrl(line.substring(name_user.length()));  
					}  
				}  
			}  
		}  
		bufferedReader.close();  
		lRet = true;  
	}  
	catch (java.io.IOException ioex) {  
		this.setUser("");  
		this.setPassword("");  
		this.setDriver("");  
		this.setUrl("");  
	}  
	return lRet;  
    }  
  
 }  
  

Sample of use, I need include ...,com.codecharge.util.cache.ICache,java.util.regex.*,java.sql.*,java.sql.DriverManager,java.sql.Connection,java.sql.SQLException"%>

  
...  
	GetValuesConnection valConn = new GetValuesConnection();  
 	boolean ret = valConn.getvaluesConnName("ConPRUEBAS");  
	if (ret == false){  
		Utils.printFatalError("Lo Siento !!!, No puedo leer el Archivo de conexiones a la DB !!!", e.getPage().getResponse());  
	}  
	Connection conn = null;  
  
	Statement stmt = null;  
	ResultSet rs = null;  
  
	try {  
		/**** Cargamos el driver ****/  
	    	Class.forName( valConn.getDriver() );  
    		/**** Realizamos la conexión ****/  
	    	conn = DriverManager.getConnection( valConn.getUrl(), valConn.getUser(), valConn.getPassword() );  
	    	/**** Ok: avisamos ****/  
  
		conn.setAutoCommit(false);   
		stmt = conn.createStatement();		  
  
		String sql = "";  
  
		sql = "SELECT TRB_CAB_EXP_SEQ.nextval idcabexp FROM dual";  
		  
		rs = stmt.executeQuery(sql);  
		while (rs.next()) {  
				id_cabexp = Utils.convertToString(rs.getInt("idcabexp"));  
		}  
  
		sql = "INSERT INTO TRB_CAB_EXP (ID,ANOEXP,NROACTA,FECINF,HORAIN,TRB_INSPECTO_ID,FECCAUSA,FIRMADA,LUGINF,ALTURA, APTO,OBSERVACIO,ETAPA,TRB_ESTADOS_ID) VALUES ('" + id_cabexp + "', '" + nselano + "', '" + nroacta + "', '" + dfecinf + "', '" + chorain + "', '" + ntrb_insp_id + "', '" + dfeccausa + "', '" + nfirmada + "', '" + nluginf + "', '" + naltura + "', '" + capto + "', '" + mobservacio + "', '" + ntetapa + "', '1'" + ")";  
		stmt.execute(sql);  
		  
		...  
  
		conn.commit();  
  
	} catch (Exception ex) {  
		try {  
			if (conn != null) {  
				conn.rollback();  
			}  
			Utils.printFatalError("Database error: " + ex.getMessage() + " -> " + pasos, e.getPage().getResponse());  
		} catch (Exception ex2) {  
			Utils.printFatalError("Database error: " + ex2.getMessage() + " -> " + pasos, e.getPage().getResponse());  
		}  
	} finally {  
			if (rs != null) {  
				rs = null;  
			}  
			if (stmt != null) {  
				stmt = null;  
			}  
			try {  
				if (conn != null) {  
					conn.setAutoCommit(true);  
					conn.close();  
					conn = null;  
					e.getPage().setRedirectString( "TRB_CAB_EXP_list.jsp" );  
				}  
			} catch (Exception ex3) {  
				Utils.printFatalError("Database error: " + ex3.getMessage() + " -> " + pasos, e.getPage().getResponse());  
			}  
  
 	}  
...

Do you think that I solved bad the Problem? For that? .

I need you to say if my solution in Good or Not.

Thank you! ! !

Regards.

Sergio.
View profile  Send private message
matheus

Posts: 386
Posted: 06/04/2009, 10:48 AM

Where do you use this last code snippet?

It's in a JSP generated by Codecharge?

It's a Record?
_________________
Matheus Trevizan

Dynamix Software Ltda.
Blumenau SC Brasil
www.dynamix.com.br
View profile  Send private message
saamondino

Posts: 33
Posted: 06/04/2009, 12:38 PM

Hi

I use the Code in a Button of "add record" and "Delete Record" of Registration, in a form.
In the buton of my Form, Envents->Server->On Click-Custom Code.
Yes, is a Custom code write for some forms that they require transactional control.

I also need to use it in processes of update of data and generation of Report using JasperReport (for the exit pdf file).

AND

YES, I use CodeCharge Studio 3.2.0.6 to Generate code.

Regards.

Sergio.
View profile  Send private message

Add new topic Subscribe to topic   


These are Community Forums for users to exchange information.
If you would like to obtain technical product help please visit http://support.yessoftware.com.

MS Access to Web

Convert MS Access to Web.
Join thousands of Web developers who build Web applications with minimal coding.

CodeCharge.com

Home   |    Search   |    Members   |    Register   |    Login


Powered by UltraApps Forum created with CodeCharge Studio
Copyright © 2003-2004 by UltraApps.com  and YesSoftware, Inc.