Catching erroneous SQL
I use a custom error page so that my users will see a
friendly message when there is an error. On that page, I send
myself an email with info about the error. So far so good.
However, if the error is with a sql statement, I want to see
the content of the query (SELECT * FROM ...) . I know that the
standard CF error page shows that but I have not figured out how to
put it in my email. I have tried error.diagnostics and
error.querystring and error.type -- but none of those is correct. I
have tried cfquery variables, but they are not passed from the page
that has an error to my error page.
This SHOULD be easy (famous last words)!
That makes sense, but I wonder if there is an easier way. I
have apps with hundreds of queries and it would be a pain to put a
cfmail after each one.
Similar Messages
-
How to catch PL/SQL: ORA-04052 error?
I need to execute a procedure that select remote objects but the remote db is a RAC DB and I only have access to one of the nodes, the remote RAC have load balancing enabled and the remote DBA can’t create a DB Service for my connection, so, I have to re-run the execution of my procedure until it connects successful to the remote DB through a db link, but I can’t catch the error ORA-12541: TNS:no listener.
Someone knows how to catch the error??
set serveroutput on
declare
function F_DATE return sysdate
is
ld_return date;
begin
begin
select sysdate into ld_return from dual@dbl_bnvalores;
exception
when others then
ld_return := f_date;
end;
return ld_return;
end F_DATE;
begin
dbms_output.put_line('Remote sysdate: '||f_date);
end;
Error at line 2
ORA-06550: line 2, column 26:
PLS-00562: a function must return a type.
ORA-06550: line 7, column 42:
PL/SQL: ORA-04052: error occurred when looking up remote object BNSAFI.DUAL@DBL_BNVALORES
ORA-00604: error occurred at recursive SQL level 1
ORA-12541: TNS:no listener
ORA-06550: line 7, column 7:
PL/SQL: SQL Statement ignoredI could confirm that you would never branch to the exception in case of no listener!
So another possibility that comes to mind is to enclose the remote select in an execute immediate and only execute it if you could establish a connection via UTL_TCP:
Something along those lines:
michaels> DECLARE
conn UTL_TCP.connection;
l_date DATE;
no_listner_excep EXCEPTION;
PRAGMA EXCEPTION_INIT (no_listner_excep, -29260);
BEGIN
conn := UTL_TCP.open_connection ('fleet', 1569);
EXECUTE IMMEDIATE 'select sysdate from dual@fleet_new'
INTO l_date;
UTL_TCP.close_connection (conn);
DBMS_OUTPUT.put_line (l_date);
EXCEPTION
WHEN no_listner_excep
THEN
DBMS_OUTPUT.put_line (SQLERRM (SQLCODE));
END;
ORA-29260: network error: TNS:no listener
PL/SQL procedure successfully completed. -
Catching java.sql.SQLException:
ok this might be a stupid question
but say i had a dataTable populated by a resultSet,
when i update the dataTable how i can catch the java.sql.SQLException's being thrown
i.e the PK exception
i know i could catch it in the web.xml but was wondering if i can catch it in my bean?Oh boy. You may want to go back and take Sun's exception tutorial. It's a fundamental concept. That having been said:
String sql = "some spiffy SQL goes here";
Connection conn = null; // initialize in a spiffy way
PreparedStatememt stmt = null;
try {
stmt = conn.prepareStatement(sql);
stmt.executeUpdate(); // assume an exception will be thrown
catch (SQLException e) {
e.printStackTrace(); // handle error processing
finally {
// ensure all resources are released regardless of success or failure
if (stmt != null) try { stmt.close(); } catch (SQLException ignore) { ignore.printStackTrace() }
if (conn != null) try { conn.close(); } catch (SQLException ignore) { ignore.printStackTrace() }
}- Saish -
How to catch PL/SQL: ORA-00904 error?
Hi ,
I am trying to run the following PL/SQL Block and have trapped error code -904( for invalid column name) in the exception section block.
The column name in the select query does not exist in the emp table and as per my understanding since I have an exceptiion handler for this error it should be handled in Exception Block.
DECLARE
invalid_column exception;
pragma exception_init (invalid_column,-00904);
no number;
BEGIN
select empn into no from emp
where ename='king';
EXCEPTION
when invalid_column then
dbms_output.put_line(Column ane does not exist)
end;
1) Can You please let me know why this is not getting caught in Exception handler
*2) What changes should I make in Exception handler section so that Invalid column name is handled in the program*
Thanks and regards
HarmeetCheck this:
SQL> ed
Wrote file afiedt.buf
1 DECLARE
2 invalid_column EXCEPTION;
3 PRAGMA EXCEPTION_INIT(invalid_column,-00904);
4 v_col_check NUMBER := 0;
5 v_col_name VARCHAR2(10) := 'OWNE';
6 BEGIN
7 select COUNT(*) INTO v_col_check
8 from all_tab_cols
9 where table_name = 'ALL_OBJECTS'
10 AND column_name = v_col_name;
11 IF (v_col_check = 0) THEN
12 RAISE invalid_column;
13 END IF;
14 EXCEPTION
15 WHEN invalid_column THEN
16 DBMS_OUTPUT.PUT_LINE('Column '||v_col_name ||' does not exist in table all_objects');
17* END;
SQL> /
Column OWNE does not exist in table all_objects
PL/SQL procedure successfully completed.
SQL> This way you can check if the column is valid or not in case you are dynamically getting the column names -
Catching Mysql sql execution status with EJB and Persistence API.
Hi:
When I insert a duplicate unique Key, the try block defined below does not catch the exception and the transaction is rolled back automatically by Glassfish.
How is the proper way to handle this to catch the duplicate status?
public class MyDbEjb extends DefaultHandler implements MyDbEjbRemote { @PersistenceContext private EntityManager em; public void createTag(Tag tag) { try { em.persist(tag); } catch ( Exception e) { System.out.println("how sorry"); } }
Thank youHi annie,
Wherever you are handling database transactions,
you'd not be able to create a Connection if database
is closed (I think you mentioned turning off the
database) then at this condition, you should
certainly throw a System level exception and stop all
processing with some meaningful flow to indicate a
failure (like display message on UI). Even
network problems are handled by exceptions... so I
don't see a reason why you didn't wrap it in the
first place.
Anyway, try handling specific exceptions rather than
the general Exception... this will give you a better
idea of what to do in case of an exception.Yes i know this. I am practicing this in my non-j2ee server applications. But the j2ee app im making, i just pass the db url in the descriptor and the app server automatically creates the connection for my app. So where would i put exception handling?
2. how can i stop my MDB from processing the same
message?Guaranteed delivery is not supposed to stop
processing. It will continue to process the message
after certain intervals till the message is
delivered. You shouldn't deliver it at all, if you
are able to detect that the database is off
The problem here is that my MDB automatically retrieves the message from the JMS queue server. Im not the one retrieving the messages manually.
My assumed behavior of topic MDB is once the a certain MDB retrieves a message it will not retrieve the same message anymore.
thank you in advance.
leigh -
Unable to catch raiseerror exception from MS SQL Server Exception in hibernate
I am using raiseerror in MS SQL Server exception to throw customized error and it is working fine in database.
But, I am unable to catch MS SQL Server Exception in hibernate. Please find the database & java syntax below.
SQL Server Syntax:-
ALTER PROCEDURE [grantiumSQL].[ERROR_MESSAGE]
@ERRMSG NVARCHAR(4000)
AS
BEGIN
-- Return if there is no error information to retrieve.
IF ERROR_NUMBER() IS NULL
RETURN;
DECLARE
@ErrorMessage NVARCHAR(4000),
@ErrorNumber INT,
@ErrorSeverity INT,
@ErrorState INT,
@ErrorLine INT,
@ErrorProcedure NVARCHAR(200);
-- Assign variables to error-handling functions that
-- capture information for RAISERROR.
SELECT
@ErrorNumber = ERROR_NUMBER(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE(),
@ErrorLine = ERROR_LINE(),
@ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-'),
@ErrorMessage = @ERRMSG
RAISERROR
@ErrorMessage,
@ErrorSeverity,
1
)WITH NOWAIT;
END;
Java Syntax:-
public void callDeleteStoreProcedure(int workflowProjectId,String status){
boolean shouldCommit = HibernateUtil.beginTxn();
Session session = HibernateUtil.currentSession();
try
// query = session.getNamedQuery("deleteWorkflowProject_ora");
Query callStoredProcedure = session.createSQLQuery("{PROCEDUR_NAME(?,?)}");
callStoredProcedure.setInteger(0, prj);
callStoredProcedure.setString(1, status);
callStoredProcedure.executeUpdate();
}catch (HibernateException e) {
e.printStackTrace();
catch (Exception e) {
e.printStackTrace();
HibernateUtil.commitTxn(shouldCommit);
Thanks in advanceHI! We have the same problem. Have you manage to resolve it?
-
Hi,
Is there any other way to catch primary key violation error other than catching the sql exception and checking the pattern in the exception trace.
Thanks in advance,Basil wrote:
Hi,
Is there any other way to catch primary key violation error other than catching the sql exception and checking the pattern in the exception trace.You could try looking at the SQL state or vendor code from the SQL exception. They might have more information, along the lines of what you are looking for.
If you are looking to avoid the exception altogether forget it. You could do a SELECT before INSERT but that of course isn't concurrency "safe" and generally is just a waste of time.
PS In future JDBC related questions should be posted into the JDBC forum. Selecting the best forum for your question gives you a better chance of getting better answers faster. -
I'm using oracle 8.1.7
How do I catch a SQL Excpetion from a JSP page that is trying to delete a Primary key of a referencing table?
When it throws the excpetion...how can I know the error code/number?
or is it just simply give out the reason/explanation without producing any numbers?????Hi,
Just put your conde inside a try - catch block like Servlets. It will work and show u all the things.
Sundar -
How to reference multiple instances of the same Java object from PL/SQL?
Dear all,
I'm experimenting with calling Java from PL/SQL.
My simple attempts work, which is calling public static [java] methods through PL/SQL wrappers from SQL (and PL/SQL). (See my example code below).
However it is the limitation of the public static methods that puzzels me.
I would like to do the following:
- from PL/SQL (in essence it needs to become a forms app) create one or more objects in the java realm
- from PL/SQL alter properties of a java object
- from PL/SQL call methods on a java object
However I fail to see how I can create multiple instances of an object and reference one particular object in the java realm through public static methods.
My current solution is the singleton pattern: of said java object I have only 1 copy, so I do not need to know a reference to it.
I can just assume that there will only ever be 1 of said object.
But I should be able to make more then 1 instance of an object.
To make it more specific:
- suppose I have the object car in the java realm
- from PL/SQL I want to create a car in the java realm
- from PL/SQL I need to give it license plates
- I need to start the engine of a scpecific car
However if I want more then 1 car then I need to be able to refrence them. How is this done?
Somehow I need to be able to execute the following in PL/SQL:
DECLARE
vMyCar_Porsche CAR;
vMyCar_Fiat CAR;
BEGIN
vMyCar_Porsche = new CAR();
vMyCar_Fiat = new CAR();
vMyCar_Porsche.setLicensePlates('FAST');
vMyCar_Porsche.startEngine();
vMyCar_Fiat.killEngine();
END;
Thanks in advance.
Best Regards,
Ruben
My current example code is the following:
JAVA:
===
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED CODAROUL."RMG/BO/RMG_OBJECT" as package RMG.BO;
public class RMG_OBJECT {
private static RMG_OBJECT instance = new RMGOBJECT();
private String rmgObjectNaam;
private RMG_OBJECT(){
this.rmgObjectNaam = "NonDetermined";
public static String GET_RMGOBJECT_NAAM () {
String toestand = null;
if (_instance == null) {toestand = "DOES NOT EXIST";} else { toestand = "EXISTS";};
System.out.println("instance : " + toestand);
System.out.println("object name is : " + _instance.rmgObjectNaam);
return _instance.rmgObjectNaam;
public static Integer SET_RMGOBJECT_NAAM (String IN)
try
_instance.rmgObjectNaam = IN;
return 1;
catch (Exception e)//catch
System.out.println("Other Exception: " + e.toString());
e.printStackTrace();
return 5;
} //catch
PL/SQL Wrapper:
==========
CREATE OR REPLACE FUNCTION CODAROUL.SET_RMGOBJECT_NAAM(NAAM IN VARCHAR2) return NUMBER AS
LANGUAGE JAVA NAME 'RMG.BO.RMG_OBJECT.SET_RMGOBJECT_NAAM (java.lang.String) return java.lang.Integer';
Calling from SQL:
==========
CALL dbms_java.set_output(2000);
select CODAROUL.GET_RMGOBJECT_NAAM() from dual;
Edited by: RubenS_BE on Apr 6, 2012 5:35 AM
Edited by: 925945 on Apr 6, 2012 5:41 AMYou can do this by manually creating a new iterator binding in your binding tab.
So instead of dragging the VO directly to the page, go to the binding tab, add a new executable iterator binding, and point to that one from your ELs in the page itself. -
How to catch exception while validating the username and password in hbm
Hi,
I do want to set the username and password dynamically in hibernate.cfg.xml
Here below is my configuration file.
{code<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>{code}
Also im getting that session factory object like the below code.
public class Sessions { private static SessionFactory sessionFactory; private static Configuration configuration = new Configuration(); static { try { String userName = GuigenserviceImpl.userName; String password = GuigenserviceImpl.password; String hostName = GuigenserviceImpl.hostName; String portNo = GuigenserviceImpl.portNo; String sId = GuigenserviceImpl.sId; configuration .setProperty("hibernate.connection.username", userName); configuration .setProperty("hibernate.connection.password", password); configuration.setProperty("hibernate.connection.url", "jdbc:oracle:thin:@" + hostName + ":" + portNo + ":" + sId); try { configuration.configure("/hibernate.cfg.xml"); sessionFactory = configuration.buildSessionFactory(); GuigenserviceImpl.strAccpted = "true"; } catch (Exception e) { e.printStackTrace(); GuigenserviceImpl.strAccpted = "false"; } } catch (HibernateException hibernateException) { GuigenserviceImpl.strAccpted = "false"; hibernateException.printStackTrace(); } catch (Throwable ex) { GuigenserviceImpl.strAccpted = "false"; ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; }
So, in this above scenario, suppose if im giving the wrong password means exception should be caught and the string variable "GuigenserviceImpl.strAccpted" should be assigned to false.
But im getting the SQL Exception only in console like wrong username and password. And finally i couldn't able to catch the exception in Sessions class, static block.
Anyone can help me in catching that SQL Exception in my Sessions class and i need to handle that SQL Exception in my class.
Im getting this following exception message in my console.
INFO: configuring from resource: /hibernate.cfg.xml Apr 6, 2009 2:47:00 PM org.hibernate.cfg.Configuration getConfigurationInputStream INFO: Configuration resource: /hibernate.cfg.xml Apr 6, 2009 2:47:00 PM org.hibernate.cfg.Configuration doConfigure INFO: Configured SessionFactory: null Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: Using Hibernate built-in connection pool (not for production use!) Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: Hibernate connection pool size: 10 Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: autocommit mode: false Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: using driver: oracle.jdbc.driver.OracleDriver at URL: jdbc:oracle:thin:@192.168.1.12:1521:orcl Apr 6, 2009 2:47:00 PM org.hibernate.connection.DriverManagerConnectionProvider configure INFO: connection properties: {user=scott, password=****} Apr 6, 2009 2:47:01 PM org.hibernate.cfg.SettingsFactory buildSettings WARNING: Could not obtain connection metadata java.sql.SQLException: ORA-01017: invalid username/password; logon denied at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70) at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:131) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:204) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:406) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399) at oracle.jdbc.driver.T4CTTIoauthenticate.receiveOauth(T4CTTIoauthenticate.java:799) at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:368) at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:508) at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:203) at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33) at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:510) at java.sql.DriverManager.getConnection(DriverManager.java:525) at java.sql.DriverManager.getConnection(DriverManager.java:140) at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110) at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:84) at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2073) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1298) at com.beyon.ezygui.server.Sessions.<clinit>(Sessions.java:39) at com.beyon.ezygui.server.GuigenserviceImpl.testRPC(GuigenserviceImpl.java:322) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
Thanks in advance.
Thanks & Regards,
Kothandaraman N.Hi,
Myself hardcoded that username and password checking like the below code.
String name = loginData.get("userName").toString();
String pswd = loginData.get("pswd").toString();
String hstName = loginData.get("hName").toString();
String prtNo = loginData.get("portNo").toString();
String sid = loginData.get("sId").toString();
SessionFactory sessionFactory = null;
try {
if (name.trim().equals(userName) && pswd.trim().equals(password)
&& hstName.trim().equals(hostName)
&& prtNo.trim().equals(portNo) && sid.trim().equals(sId)) {
sessionFactory = Sessions.getSessionFactory();
strAccpted = "true";
} else {
strAccpted = "false";
} catch (Exception e) {
e.printStackTrace();
strAccpted = "false";
}I have my own values in string objects, then comparing that values with the values from login form. If both values are matching, then i will do configurations in hibernate.
ResourceBundle resourceBundle = ResourceBundle
.getBundle("com.beyon.ezygui.server.Queries");
public static final String connection_url = resourceBundle
.getString("connection.url");
public static final String userName = resourceBundle.getString("userName");
public static final String password = resourceBundle.getString("password");
public static final String hostName = resourceBundle.getString("hostName");
public static final String portNo = resourceBundle.getString("portNo");
public static final String sId = resourceBundle.getString("sId");The above are the String objects i'm checking for the match with values from login form.
Thanks & Regards,
Kothandaraman N. -
Java API for running entire ".sql" files on a remote DB ( mySQL or Oracle)?
Hi,
Would anyone happen to know if there's a java API for executing entire ".sql" files (containing several different SQL commands), on a remote database server ?
It's enough if the API works with MySQL and/or Oracle.
Just to demonstrate what i'm looking for:
Suppose you've created sql file "c:/test.sql" with several script lines:
-- test.sql:
insert into TABLE1 values(3,3);
insert into TABLE1 values(5,5);
create table TABLE2 (name VARCHER) ENGINE innoDB; -- MYSQL specific
Then the java API should look something like:
// Dummy java code:
String driver="com.mysql.jdbc.Driver";
String url= "jdbc:mysql://localhost:3306/myDb";
SomeAPI.executeScriptFile( "c:/test.sql", driver, url);
Thanks.No such a API, but it's easy to parse all sqls in a file, then run those command:
For instance:
import java.sql.*;
import java.util.Properties;
/* A demo show how to load some sql statements. */
public class testSQL {
private final static Object[] getSQLStatements(java.util.Vector v) {
Object[] statements = new Object[v.size()];
Object temp;
for (int i = 0; i < v.size(); i++) {
temp = v.elementAt(i);
if (temp instanceof java.util.Vector)
statements[i] = getSQLStatements( (java.util.Vector) temp);
else
statements[i] = temp;
return statements;
public final static Object[] getSQLStatements(String sqlFile) throws java.
io.IOException {
java.util.Vector v = new java.util.Vector(1000);
try {
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.
FileReader(sqlFile));
java.util.Vector batchs = new java.util.Vector(10);
String temp;
while ( (temp = br.readLine()) != null) {
temp = temp.trim();
if (temp.length() == 0)
continue;
switch (temp.charAt(0)) {
case '*':
case '"':
case '\'':
// System.out.println(temp);
break; //Ignore any line which begin with the above character
case '#': //Used to begin a new sql statement
if (batchs.size() > 0) {
v.addElement(getSQLStatements(batchs));
batchs.removeAllElements();
break;
case 'S':
case 's':
case '?':
if (batchs.size() > 0) {
v.addElement(getSQLStatements(batchs));
batchs.removeAllElements();
v.addElement(temp);
break;
case '!': //Use it to get a large number of simple update statements
if (batchs.size() > 0) {
v.addElement(getSQLStatements(batchs));
batchs.removeAllElements();
String part1 = temp.substring(1);
String part2 = br.readLine();
for (int i = -2890; i < 1388; i += 39)
batchs.addElement(part1 + i + part2);
for (int i = 1890; i < 2388; i += 53) {
batchs.addElement(part1 + i + part2);
batchs.addElement(part1 + i + part2);
for (int i = 4320; i > 4268; i--) {
batchs.addElement(part1 + i + part2);
batchs.addElement(part1 + i + part2);
for (int i = 9389; i > 7388; i -= 83)
batchs.addElement(part1 + i + part2);
v.addElement(getSQLStatements(batchs));
batchs.removeAllElements();
break;
default:
batchs.addElement(temp);
break;
if (batchs.size() > 0) {
v.addElement(getSQLStatements(batchs));
batchs.removeAllElements();
br.close();
br = null;
catch (java.io.FileNotFoundException fnfe) {
v.addElement(sqlFile); //sqlFile is a sql command, not a file Name
Object[] statements = new Object[v.size()];
for (int i = 0; i < v.size(); i++)
statements[i] = v.elementAt(i);
return statements;
public static void main(String argv[]) {
try {
String url;
Object[] statements;
switch (argv.length) {
case 0: //Use it for the simplest test
case 1:
url = "jdbc:dbf:/.";
if (argv.length == 0) {
statements = new String[1];
statements[0] = "select * from test";
else
statements = argv;
break;
case 2:
url = argv[0];
statements = getSQLStatements(argv[1]);
break;
default:
throw new Exception(
"Syntax Error: java testSQL url sqlfile");
Class.forName("com.hxtt.sql.dbf.DBFDriver").newInstance();
//Please see Connecting to the Database section of Chapter 2. Installation in Development Document
Properties properties = new Properties();
Connection con = DriverManager.getConnection(url, properties);
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
//Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
// stmt.setMaxRows(0);
stmt.setFetchSize(10);
final boolean serializeFlag = false;//A test switch to serialize/deserialize the resultSet
ResultSet rs;
for (int i = 0; i < statements.length; i++) {
if (statements[i] instanceof java.lang.String) {
String temp = (java.lang.String) statements;
switch (temp.charAt(0)) {
case 'S':
case 's':
case '?':
System.out.println(temp);
rs = stmt.executeQuery(temp);
if (serializeFlag) {
// serialize the resultSet
try {
java.io.FileOutputStream fileOutputStream = new
java.io.FileOutputStream("testrs.tmp");
java.io.ObjectOutputStream
objectOutputStream = new java.io.
ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(rs);
objectOutputStream.flush();
objectOutputStream.close();
fileOutputStream.close();
catch (Exception e) {
System.out.println(e);
e.printStackTrace();
System.exit(1);
rs.close(); //Let the CONCUR_UPDATABLE resultSet release its open files at once.
rs = null;
// deserialize the resultSet
try {
java.io.FileInputStream fileInputStream = new
java.io.FileInputStream("testrs.tmp");
java.io.ObjectInputStream objectInputStream = new
java.io.ObjectInputStream(
fileInputStream);
rs = (ResultSet) objectInputStream.
readObject();
objectInputStream.close();
fileInputStream.close();
catch (Exception e) {
System.out.println(e);
e.printStackTrace();
System.exit(1);
ResultSetMetaData resultSetMetaData = rs.
getMetaData();
int iNumCols = resultSetMetaData.getColumnCount();
for (int j = 1; j <= iNumCols; j++) {
// System.out.println(resultSetMetaData.getColumnName(j));
/* System.out.println(resultSetMetaData.getColumnType(j));
System.out.println(resultSetMetaData.getColumnDisplaySize(j));
System.out.println(resultSetMetaData.getPrecision(j));
System.out.println(resultSetMetaData.getScale(j));
System.out.println(resultSetMetaData.
getColumnLabel(j)
+ " " +
resultSetMetaData.getColumnTypeName(j));
Object colval;
rs.beforeFirst();
long ncount = 0;
while (rs.next()) {
// System.out.print(rs.rowDeleted()+" ");
ncount++;
for (int j = 1; j <= iNumCols; j++) {
colval = rs.getObject(j);
System.out.print(colval + " ");
System.out.println();
rs.close(); //Let the resultSet release its open tables at once.
rs = null;
System.out.println(
"The total row number of resultset: " + ncount);
System.out.println();
break;
default:
int updateCount = stmt.executeUpdate(temp);
System.out.println(temp + " : " + updateCount);
System.out.println();
else if (statements[i] instanceof java.lang.Object[]) {
int[] updateCounts;
Object[] temp = (java.lang.Object[]) statements[i];
try {
for (int j = 0; j < temp.length; j++){
System.out.println( temp[j]);
stmt.addBatch( (java.lang.String) temp[j]);
updateCounts = stmt.executeBatch();
for (int j = 0; j < temp.length; j++)
System.out.println((j+1)+":"+temp[j]);
for (int j = 0; j < updateCounts.length; j++)
System.out.println((j+1)+":" +updateCounts[j]);
catch (java.sql.BatchUpdateException e) {
updateCounts = e.getUpdateCounts();
for (int j = 0; j < updateCounts.length; j++)
System.out.println((j+1)+":"+updateCounts[j]);
java.sql.SQLException sqle = e;
do {
System.out.println(sqle.getMessage());
System.out.println("Error Code:" +
sqle.getErrorCode());
System.out.println("SQL State:" + sqle.getSQLState());
sqle.printStackTrace();
while ( (sqle = sqle.getNextException()) != null);
catch (java.sql.SQLException sqle) {
do {
System.out.println(sqle.getMessage());
System.out.println("Error Code:" +
sqle.getErrorCode());
System.out.println("SQL State:" + sqle.getSQLState());
sqle.printStackTrace();
while ( (sqle = sqle.getNextException()) != null);
stmt.clearBatch();
System.out.println();
stmt.close();
con.close();
catch (SQLException sqle) {
do {
System.out.println(sqle.getMessage());
System.out.println("Error Code:" + sqle.getErrorCode());
System.out.println("SQL State:" + sqle.getSQLState());
sqle.printStackTrace();
while ( (sqle = sqle.getNextException()) != null);
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace(); -
How to echo the SQL command in JDBC?
When we use a PreparedStatement and execute query, is there a way to get the exact SQL command
sent to the server without any '?' marks? That would be an aid in debugging. Or is such a facility server-pecific? I am using MySQL with JDBC.
Thank you.Why I want to see the SQL command now is that I am getting a nagging SQLException in the following
code. Would someone tell me why this code fails?
//Database connection successful.
//conn and pstmt are successfully created.
//variables 'pid' and 'subfolder' are already evaluated, and confirmed that they have valid values
int sub_id = 0;
String myquery = null;
ResultSet rs1 = null;
try{
myquery = "SELECT j15c_directory_id FROM j15t_directory WHERE (j15c_parent_id = ? AND j15c_name = ?)";
pstmt = conn.prepareStatement(myquery);
pstmt.setInt(1,pid);
pstmt.setString(2,subfolder);
rs1 = pstmt.executeQuery();
rs1.next();
sub_id =rs1.getInt("j15c_directory_id");
catch(java.sql.SQLException e1){
System.err.println("SQLException: " + e1.getMessage());
The error message I'm getting is "Before start of result set ". -
Unable to compile the java class in the SQL PLUS
Hi Team,
I am unable to compile the java class in the SQL PLUS in dev1 and dev2. It is giving the following error.
But the same class get Compiled in the Toad(Tool) without any error and working fine. Could someone help me
What to do for this for your reference ,Attaching the java class file.
“ORA-29536: badly formed source: Encountered "<EOF>" at line 1, column 28.
Was expecting one of:
----------------------Here is the Java class Code.....................
create or replace and compile java source named "XXVM_ZipFileUtil_Ela"
as
import java.math.BigDecimal;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import oracle.sql.*;
import oracle.jdbc.*;
import java.sql.*;
import java.io.*;
public class XXVM_ZipFileUtil_Ela
public static oracle.sql.BLOB getZipFile(
oracle.sql.CHAR zipFilePathCHAR, oracle.sql.CHAR zipFileNameCHAR,
int fileBufferSize, int zipFileBufferSize,
boolean deleteZipFile, java.sql.Array fileNames, java.sql.Array fileContents, java.sql.Array fileContentsLength)
throws IllegalArgumentException, FileNotFoundException, IOException, java.sql.SQLException
String zipFilePath = (zipFilePathCHAR == null) ? null : zipFilePathCHAR.stringValue();
String zipFileName = (zipFileNameCHAR == null) ? null : zipFileNameCHAR.stringValue();
String zipPathAndFileName = new String(
new String(zipFilePath == null || zipFilePath == "" ? "/tmp/" : zipFilePath) +
new String(zipFileName == null || zipFileName == "" ? System.currentTimeMillis() + ".zip" : zipFileName));
byte[] buffer = new byte[fileBufferSize == 0 ? 100000000 : fileBufferSize];
try
Connection conn = DriverManager.getConnection("jdbc:default:connection:");
oracle.sql.CLOB[] fileContentsCLOB = (oracle.sql.CLOB[])fileContents.getArray();
String[] fileNamesString = (String[])fileNames.getArray();
BigDecimal[] fileContentsLengthNumber = (BigDecimal[])fileContentsLength.getArray();
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPathAndFileName));
zipOut.setLevel(Deflater.DEFAULT_COMPRESSION);
for (int i = 0; i < fileNamesString.length; i++) {
System.out.println(i);
zipOut.putNextEntry(new ZipEntry(fileNamesString));
InputStream asciiStream = fileContentsCLOB[i].getAsciiStream(1L);
int asciiReadCount = asciiStream.read(buffer,0,fileContentsLengthNumber[i].intValue());
zipOut.write(buffer, 0, fileContentsLengthNumber[i].intValue());
zipOut.closeEntry();
zipOut.close();
byte zipFileContents[] = new byte[zipFileBufferSize == 0 ? 100000000 : zipFileBufferSize];
FileInputStream zipIn = new FileInputStream(zipPathAndFileName);
int byteCount = zipIn.read(zipFileContents);
zipIn.close();
byte returnFileContents[] = new byte[byteCount];
System.arraycopy(zipFileContents,0,returnFileContents,0,byteCount);
String returnFileContentsString = new String(returnFileContents);
if (deleteZipFile)
boolean deletedFile = (new File(zipPathAndFileName)).delete();
oracle.sql.BLOB returnFileContentsBLOB = null;
returnFileContentsBLOB = BLOB.createTemporary(conn, true, BLOB.DURATION_SESSION);
returnFileContentsBLOB.open(BLOB.MODE_READWRITE);
//OutputStream tempBlobWriter = returnFileContentsBLOB.getBinaryOutputStream();
OutputStream tempBlobWriter = returnFileContentsBLOB.setBinaryStream(1);
tempBlobWriter.write(returnFileContents);
tempBlobWriter.flush();
tempBlobWriter.close();
returnFileContentsBLOB.close();
return returnFileContentsBLOB;
catch (IllegalArgumentException ex) {
ex.printStackTrace();
throw ex;
catch (FileNotFoundException ex) {
ex.printStackTrace();
throw ex;
catch (IOException ex)
ex.printStackTrace();
throw ex;
catch (java.sql.SQLException ex)
ex.printStackTrace();
throw ex;860411 wrote:
Hi Team,
I am unable to compile the java class in the SQL PLUS in dev1 and dev2. It is giving the following error.
But the same class get Compiled in the Toad(Tool) without any error and working fine. Could someone help me
What to do for this for your reference ,Attaching the java class file.
“ORA-29536: badly formed source: Encountered "<EOF>" at line 1, column 28.
Was expecting one of:
I believe the error message is clear and self-explanatory.
----------------------Here is the Java class Code.....................
create or replace and compile java source named "XXVM_ZipFileUtil_Ela"
as
import java.math.BigDecimal;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import oracle.sql.*;
import oracle.jdbc.*;
import java.sql.*;
import java.io.*;
public class XXVM_ZipFileUtil_Ela
public static oracle.sql.BLOB getZipFile(
oracle.sql.CHAR zipFilePathCHAR, oracle.sql.CHAR zipFileNameCHAR,
int fileBufferSize, int zipFileBufferSize,
boolean deleteZipFile, java.sql.Array fileNames, java.sql.Array fileContents, java.sql.Array fileContentsLength)
throws IllegalArgumentException, FileNotFoundException, IOException, java.sql.SQLException
String zipFilePath = (zipFilePathCHAR == null) ? null : zipFilePathCHAR.stringValue();
String zipFileName = (zipFileNameCHAR == null) ? null : zipFileNameCHAR.stringValue();
String zipPathAndFileName = new String(
new String(zipFilePath == null || zipFilePath == "" ? "/tmp/" : zipFilePath) +
new String(zipFileName == null || zipFileName == "" ? System.currentTimeMillis() + ".zip" : zipFileName));
byte[] buffer = new byte[fileBufferSize == 0 ? 100000000 : fileBufferSize];
try
Connection conn = DriverManager.getConnection("jdbc:default:connection:");
oracle.sql.CLOB[] fileContentsCLOB = (oracle.sql.CLOB[])fileContents.getArray();
String[] fileNamesString = (String[])fileNames.getArray();
BigDecimal[] fileContentsLengthNumber = (BigDecimal[])fileContentsLength.getArray();
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPathAndFileName));
zipOut.setLevel(Deflater.DEFAULT_COMPRESSION);
for (int i = 0; i < fileNamesString.length; i++) {
System.out.println(i);
zipOut.putNextEntry(new ZipEntry(fileNamesString));
InputStream asciiStream = fileContentsCLOB[i].getAsciiStream(1L);
int asciiReadCount = asciiStream.read(buffer,0,fileContentsLengthNumber[i].intValue());
zipOut.write(buffer, 0, fileContentsLengthNumber[i].intValue());
zipOut.closeEntry();
zipOut.close();
byte zipFileContents[] = new byte[zipFileBufferSize == 0 ? 100000000 : zipFileBufferSize];
FileInputStream zipIn = new FileInputStream(zipPathAndFileName);
int byteCount = zipIn.read(zipFileContents);
zipIn.close();
byte returnFileContents[] = new byte[byteCount];
System.arraycopy(zipFileContents,0,returnFileContents,0,byteCount);
String returnFileContentsString = new String(returnFileContents);
if (deleteZipFile)
boolean deletedFile = (new File(zipPathAndFileName)).delete();
oracle.sql.BLOB returnFileContentsBLOB = null;
returnFileContentsBLOB = BLOB.createTemporary(conn, true, BLOB.DURATION_SESSION);
returnFileContentsBLOB.open(BLOB.MODE_READWRITE);
//OutputStream tempBlobWriter = returnFileContentsBLOB.getBinaryOutputStream();
OutputStream tempBlobWriter = returnFileContentsBLOB.setBinaryStream(1);
tempBlobWriter.write(returnFileContents);
tempBlobWriter.flush();
tempBlobWriter.close();
returnFileContentsBLOB.close();
return returnFileContentsBLOB;
catch (IllegalArgumentException ex) {
ex.printStackTrace();
throw ex;
catch (FileNotFoundException ex) {
ex.printStackTrace();
throw ex;
catch (IOException ex)
ex.printStackTrace();
throw ex;
catch (java.sql.SQLException ex)
ex.printStackTrace();
throw ex;
The last two lines above should be
/Srini -
Java.sql.SQLException: Fail to convert between UTF8 and UCS2: failUTF8Conv
Hi all,
I am writing a servlet that connects to Oracle 8.0.6 through jdbc for jdk1.2 on NT 4.0
English version and it works fine.
But when the servlet is deployed to a solaris with Oracle 8.0.5 (not a typo, the oracle on
NT is 8.0.6 and oracle on solaris is 8.0.5) and jdbc for jdk1.2 (of course, for Solaris),
the servlet failed with the Exception:
java.sql.SQLException: Fail to convert between UTF8 and UCS2: failUTF8Conv
(I am using JRun 3.0 as the application and web server for both NT and Solaris)
(The database in both the NT and solaris platform are using UTF8 charset)
My servlet looks like this: (dbConn is a Connection object proved to be connected to Oracle
in previous segment of the same method):
String strSQL = "SELECT * FROM test";
try { Statement stmt = dbConn.createStatement();
ResultSet rs = stmt.execute(strSQL);
while (rs.next()) {
out.println("id = " + rs.getInt("id"));
System.out.println("id written");
out.println("name = " + rs.getString("name")); // <-- this is the line the
exception is thrown
System.out.println("name written");
} catch (java.sql.SQLException e) {
System.out.println("SQL Exception");
System.out.println(e);
The definition of the "test" table is:
create table test(
id number(10,0),
name varchar2(30));
There are about 10 rows exists in the table "test", in which all rows contains ONLY chinese
characters in the "name" field.
And when I view the System log, the string "id written" is shown EXACTLY ONCE and then there
is:
SQL Exception
java.sql.SQLException: Fail to convert between UTF8 and UCS2: failUTF8Conv
That means the resultset is fetch back from the database correctly. The problem arise only
during the getString("name") method.
Again, this problem only happens when the servlet is run on the solaris platform.
At first I would expect there are some strange code shown on the web page rather than having
an exception. I know that I should use getBytes to convert between different encodings, but
that's another story.
One more piece of information: When all the rows contains ascii characters in their "name"
field, the servlet works perfectly even in solaris.
If anyone knows why and how to tackle the problem please let me know. You can feel free to
send email to me at [email protected]
Many thanks,
Ben
nullHi all,
For the problem I previously posted, I found that Oracle had had such bug filed before in Oracle 7.3.2 (something like that) and is classified to be NOT A BUG.
A further research leads me to the document of Oracle that the error message:
"java.sql.SQLException: Fail to convert between UTF8 and UCS2: failUTF8Conv"
is a JDBC driver error message of error number ORA-17037.
I'm still wondering why this behaviour will happen only in Solaris platform. The servlet on an NT machine I am using (which has an Oracle 8.0.6 and jdbc for jdk 1.2 running) is working just fine. I also suspect that this may be some sort of mistakes from jdbc driver.
Nevertheless, I have found a way to work around the problem that I cannot get non-English string from Oracle in Solaris and I would like to share it with you all here.
Before I go on, I found that there are many people out there on the web that encounter the same problem. (Some of which said s/he has been working on this problem for a month). As a result, if you find this way of working around the problem does help you, please tell those who have the same problem but don't know how to tackle. Thanks very much.
Here's the way I work it out. It's kinda simple, but it does work:
Instead of using:
String abc = rs.getString("SomeColumnContainsNonEnglishCharacters");
I used this:
String abc = new String(rs.getBytes("SomeColumnContainsNonEnglishCharacters"));
This will give you a string WITH YOUR DEFAULT CHARSET (or ENCODING) from your system.
If you want to convert the string read to some other encoding type, say Big5, you can do it like this:
String abc = new String(rs.getBytes("SomeColumneContainsNonEnglishCharacters"), "BIG5");
Again, it's simple, but it works.
Finally, if anyone knows why the fail to convert problem happens, please kindly let me know by leaving a word in [email protected]
Again, thanks to those of you who had tried to help me out.
Creambun
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by creambun creambun ([email protected]):
Hi all,
I am writing a servlet that connects to Oracle 8.0.6 through jdbc for jdk1.2 on NT 4.0
English version and it works fine.
But when the servlet is deployed to a solaris with Oracle 8.0.5 (not a typo, the oracle on
NT is 8.0.6 and oracle on solaris is 8.0.5) and jdbc for jdk1.2 (of course, for Solaris),
the servlet failed with the Exception:
java.sql.SQLException: Fail to convert between UTF8 and UCS2: failUTF8Conv
(I am using JRun 3.0 as the application and web server for both NT and Solaris)
(The database in both the NT and solaris platform are using UTF8 charset)
My servlet looks like this: (dbConn is a Connection object proved to be connected to Oracle
in previous segment of the same method):
String strSQL = "SELECT * FROM test";
try { Statement stmt = dbConn.createStatement();
ResultSet rs = stmt.execute(strSQL);
while (rs.next()) {
out.println("id = " + rs.getInt("id"));
System.out.println("id written");
out.println("name = " + rs.getString("name")); // <-- this is the line the
exception is thrown
System.out.println("name written");
} catch (java.sql.SQLException e) {
System.out.println("SQL Exception");
System.out.println(e);
The definition of the "test" table is:
create table test(
id number(10,0),
name varchar2(30));
There are about 10 rows exists in the table "test", in which all rows contains ONLY chinese
characters in the "name" field.
And when I view the System log, the string "id written" is shown EXACTLY ONCE and then there
is:
SQL Exception
java.sql.SQLException: Fail to convert between UTF8 and UCS2: failUTF8Conv
That means the resultset is fetch back from the database correctly. The problem arise only
during the getString("name") method.
Again, this problem only happens when the servlet is run on the solaris platform.
At first I would expect there are some strange code shown on the web page rather than having
an exception. I know that I should use getBytes to convert between different encodings, but
that's another story.
One more piece of information: When all the rows contains ascii characters in their "name"
field, the servlet works perfectly even in solaris.
If anyone knows why and how to tackle the problem please let me know. You can feel free to
send email to me at [email protected]
Many thanks,
Ben<HR></BLOCKQUOTE>
null -
Cathcing "end of file on communication channel" in pl/sql
Hello
I have a pl/sql package that accesses a remote database via dblink and copies rows into the current database (simple insert-select).
From time to time the remote database shuts down (some kind of cold backup - that cannot be changed) and then, if my package was working then it gets "end of file on communication channel" and ends.
My session isnt killed, but disconnects from the remote database so I wonder if I can catch this error as an exception, tell my program to wait a while and then try connecting to the remote database again and restart the transaction.
Is it possible to catch this error ? if yes then will it just reconnect to the remote database or should I explicitly reconnect (accessing via dblink usually implicitly connects) ?
Thanks
GuyDespite the error number is 3113 you need to catch 2068:
SQL> set serverout on
SQL> DECLARE
remote3113 EXCEPTION;
PRAGMA EXCEPTION_INIT (remote3113, -3113);
remote2068 EXCEPTION;
PRAGMA EXCEPTION_INIT (remote2068, -2068);
BEGIN
FOR c IN (SELECT * FROM all_objects@oracle)
LOOP
NULL;
END LOOP;
EXCEPTION
WHEN remote3113
THEN
DBMS_OUTPUT.put_line ('3113 Error: ' || SQLERRM);
WHEN remote2068
THEN
DBMS_OUTPUT.put_line ('2068 Error: ' || SQLERRM);
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line ('Other Error: ' || SQLERRM);
END;
2068 Error: ORA-02068: following severe error from ORACLE
ORA-03113: end-of-file on communication channel
PL/SQL procedure successfully completed.;)
Maybe you are looking for
-
I just built a new Computer and sucessfully moved my iTunes Library and music over (Windows 7, Itunes 10.3.1.55). I am getting a message on the cover flow view that states, "iTunes is unable to browse album covers on this computer". This Cover Art
-
Where is the "print" tab when I right click album artwork?
Would love to print out cd covers like I have been doing for the past 8 years. Did it go away when I updated?
-
Hi, In the past, I have configured NWDI for MII 12.1 system and used NWDS for deploying the code to production system. For 12.2 version, I see some SAP document says there is an enhancement to MII transport mechanism using NWDI. Can anybody explain w
-
I am new to iDVD and jere is the issue. I brought my movie in with 12 chapters in the "Revolution" theme. On the first page it has "Scenes 1-6" with just a simple link to that chapter. But when I go to the next page it has "Scenes 7-12" but with litt
-
any suggestions?