Gettint try and catch events after deleting row sql - sql

Hello guys whenever I try to delete a row using a radiobutton, I get both try and catch messages, when it is supposed to be just 1 of them, I have this code
Here's my calling button method
if(request.getParameter("btnEliminar") != null)
{
String value;
int codParse;
OC_DAO objDAO = new OC_DAO();
valor = request.getParameter("rbSel");
codParse = Integer.parseInt(valor);
objDAO.DeleteRow(codParse);
}
Here's my java code
public void DeleteRow(int codDet)
{
try
{
cn = Conexion.getConexion();
pt = cn.prepareStatement("DELETE "
+ "FROM detalleProd "
+ "WHERE codDet = ?");
pt.setInt(1, codDet);
pt.executeUpdate();
System.out.println("ROW DELETED ON CODDET: " + codDet);
rs.close();
pt.close();
cn.close();
}
catch(Exception exc)
{
System.out.println("Error while deleting");
System.out.println(exc.toString());
}
}
And here's my log
Información: ROW DELETED ON CODDET: 48
Información: Error while deleting
Información: java.lang.NullPointerException

The reason is due to rs.close();, you have not set value of rs,it's null and can not be closed,you just need to remove this line of code.
Your code seems very strange,I do not have see where you declare rs,it will compile error in your IDE.

Related

DB2 - ERRORCODE=-4229, SQLSTATE=null

I'm using a batch class in EJB to INSERT more than 100 rows in the same commit using the command line executeBatch in the DB2.
When I execute the command shows this error: ERRORCODE=-4229, SQLSTATE=null.
The ID sequence is IDENTITY clause on the CREATE TABLE.
Table:
CREATE TABLE table (col1 INT,
col2 DOUBLE,
col3 INT NOT NULL GENERATED ALWAYS AS IDENTITY)
Does anyone have any idea?
ERROR:
Caused by: nested exception is: com.ibm.db2.jcc.am.BatchUpdateException: [jcc][t4][102][10040][4.24.97] Batch failure. The batch was submitted, but at least one exception occurred in an individual batch member.
Use getNextException() to retrieve exceptions for specific batch elements. ERRORCODE=-4229, SQLSTATE=null
It's not an answer, but a suggestion to handle Db2 exceptions to have an ability to deal with such errors.
If you are unable to rewrite your error handling, the only thing you can to is to enable JDBC trace on the client or/and set the Db2 dbm cfg DIAGLEVEL parameter to 4.
PreparedStatement pst = null;
try
{
pst = ...;
...
int [] updateCounts = pst.executeBatch();
System.out.println("Batch results:");
for (int i = 0; i < updateCounts.length; i++)
System.out.println(" Statement " + i + ":" + updateCounts[i]);
} catch (SQLException ex)
{
while (ex != null)
{
if (ex instanceof com.ibm.db2.jcc.DB2Diagnosable)
{
com.ibm.db2.jcc.DB2Diagnosable db2ex = com.ibm.db2.jcc.DB2Diagnosable) ex;
com.ibm.db2.jcc.DB2Sqlca sqlca = db2ex.getSqlca();
if (sqlca != null)
{
System.out.println("SQLCODE: " + sqlca.getSqlCode());
System.out.println("MESSAGE: " + sqlca.getMessage());
}
else
{
System.out.println("Error code: " + ex.getErrorCode());
System.out.println("Error msg : " + ex.getMessage());
}
}
else
{
System.out.println("Error code (no db2): " + ex.getErrorCode());
System.out.println("Error msg (no db2): " + ex.getMessage());
}
if (ex instanceof BatchUpdateException)
{
System.out.println("Contents of BatchUpdateException:");
System.out.println(" Update counts: ");
System.out.println(" Statement.SUCCESS_NO_INFO: " + Statement.SUCCESS_NO_INFO);
System.out.println(" Statement.EXECUTE_FAILED : " + Statement.EXECUTE_FAILED);
BatchUpdateException buex = (BatchUpdateException) ex;
int [] updateCounts = buex.getUpdateCounts();
for (int i = 0; i < updateCounts.length; i++)
System.out.println(" Statement " + i + ":" + updateCounts[i]);
}
ex = ex.getNextException();
}
}
...

Whats wrong with this SQL Command? It should work

Whats wrong with this sql code? Syntax should be ok or not?
public void setArtikelIdRegalfach(ArrayList <Integer> arikel_ID, int Regal_ID) { // Setzt die Regalfach ArtikelID
try {
String query = "UPDATE WARENLISTE SET ARTIKEL_ID Values (" + arikel_ID + ") WHERE Regal_ID = " + Regal_ID;
st.executeUpdate(query);
}
catch(Exception e) {
System.out.println(e);
}
}
Update statements in SQL do not take a VALUES clause. On top of this, you should be using a prepared statement. Here is a corrected version:
String sql = "UPDATE WARENLISTE SET ARTIKEL_ID = ? WHERE Regal_ID = ?";
try (Connection conn = DriverManager.getConnection("...");
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, arikel_ID);
ps.setInt(2, Regal_ID);
ps.executeUpdate();
}
catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}

Creating Trigger to auto-increment id by sequence in JDBC

I am writing methods through JDBC to create a table and a sequence to recall in a Trigger, I want to set up an id column which auto-increments before every insert on the table. I succeeded in building both the createTable method and the createSequence method in the DAO, but when I run the method to create the Trigger I got the java.sql.SQLException: Missing IN or OUT parameter at index:: 1
public void createTrigger() {
PreparedStatement ps;
StringBuilder queryTrigger = new StringBuilder();
queryTrigger.append("CREATE OR REPLACE TRIGGER ");
queryTrigger.append(Tables.getInstance().getName() + "_INSERTED\n");
queryTrigger.append("BEFORE INSERT ON " + Tabelle.getInstance().getName());
queryTrigger.append("\nFOR EACH ROW\n");
queryTrigger.append("BEGIN\n");
queryTrigger.append("SELECT " + Tables.getInstance().getName() + "SEQ.NEXTVAL\n");
queryTrigger.append("INTO :new.id\n");
queryTrigger.append("FROM dual;\n ");
queryTrigger.append("END;\n");
queryTrigger.append("/\n");
queryTrigger.append("ALTER TRIGGER " +Tabelle.getInstance().getName() + "_INSERTED ENABLE\n");
queryTrigger.append("/\n");
String stringQueryTrigger = queryTrigger.toString();
Connection conn = JDBCUtility.openConnection();
try {
ps = (PreparedStatement) conn.prepareStatement(stringQueryTrigger);
ps.executeUpdate();
ps.close();
} catch(SQLException e) {
e.printStackTrace();
}
JDBCUtility.closeConnection(conn);}
Here instead the creation of the table does actually work even if I don't
write the classic lines with parametrized "?" for the preparedStatement.setString(index, String)
public void createTable(Columns c) {
PreparedStatement ps;
StringBuilder query = new StringBuilder();
query.append("CREATE TABLE " + Tabelle.getInstance().getName() + "(");
query.append(Columns.getInstance().getColumnName() + " ");
query.append(Columns.getInstance().getDataType());
if(Columns.getInstance().isNullOrNot() == true) {
query.append(" NOT NULL");
}
else {
query.append("");
}
if(Columns.getInstance().isPrimaryKeyOrNot() == true) {
query.append(" PRIMARY KEY)");
}
else {
query.append(")");
}
String queryToString = query.toString();
Connection conn = JDBCUtility.openConnection();
try {
ps = (PreparedStatement) conn.prepareStatement(queryToString);
ps.executeUpdate();
ps.close();
} catch(SQLException e) {
e.printStackTrace();
}
JDBCUtility.closeConnection(conn);
}
//EDIT
turns out that is enough to substitute the PreparedStatement with a simple Statement, to get rid of the indexes mechanism and get the DB to accept the query
I would suggest creating an auto-increment sequnce in oracle that can be used for all ids and just add the string id.NextVal to the string query
What I mean is:
Rem in oracle create sequence
CREATE SEQUENCE ID
START BY 1
INCREMENT 1
// in java to execute query
String query = "INSERT INTO TABLE VALUES(ID.NEXTVAL);" ;
//rest of code

Increasing the size of Varchar2() in oracle

Is it possible to increment the size of a column (say varchar2(25)) by 50? To be precise, I am not looking for something like this:
ALTER TABLE <Table_name> modify <Column_name> varchar2(75);
Rather, I am inquisitive about something that will increase the size by 50 or some other integer constant without the explicit calculation on the programmer part.
PS: Please comment if I am not clear.
Just to be clear, it appears you're asking for a way to add a fixed value to the column size without knowing what the original size is (hence asking how to add 50 and disallowing setting it directly to 75, which would require knowing it was 25 to start with).
Most databases provide system tables or views which give you the metadata about various objects. For example, DB2/z has sysibm.syscolumns and Oracle has all_tab_columns as shown in this link.
If you wanted to expand the column by 50 without knowing in advance what the size was, you could simply consult the metadata to get the current size and just add 50, constructing a statement to do it for you.
In other words, use something like:
select char_length from all_tab_columns
where owner = '<Table_owner>'
and table_name = '<Table_name>'
and column_name = '<Column_name>'
then extract that number from the recordset, add 50, and use that to dynamically construct and execute an alter table statement, similar to the one in your question that assumes you already know the length you want.
You can also use the user_tab_columns view if you're only concerned with your own tables rather than all those you can see. In that case, you don't need to concern yourself with the where owner = clause.
Although this sample code is specific to the DB2/z metadata, it wouldn't take much to convert it to the corresponding Oracle version:
import java.io.*;
import java.util.*;
import java.sql.*;
class chgcolsz {
public void chgcolsz() {}
public static void main (String args[]) {
Connection conn;
try {
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
conn = DriverManager.getConnection(
"jdbc:db2://MyBox:9999/MyInstance", "Me", "MyPassword");
conn.setAutoCommit (true);
} catch (Exception e) {
System.out.println ("** Error: DB connect: " + e);
e.printStackTrace();
return;
}
String cmd =
"select length from sysibm.syscolumns" +
" where tbcreator = 'PAX'" +
" and tbname = 'XYZZY'" +
" and name = 'COLUMN1'";
ResultSet rs;
try {
Statement sttmnt = conn.createStatement();
rs = sttmnt.executeQuery (cmd);
} catch (Exception e) {
rs = null;
System.out.println ("** Warning: rowset create: '" +
cmd + "': " + e);
e.printStackTrace();
}
int sz = -1;
if (rs != null) {
try {
rs.next();
sz = rs.getInt(1);
rs.close();
} catch (Exception e) {
System.out.println ("** Warning: rowset close: " + e);
e.printStackTrace();
};
}
if (sz != -1) {
System.out.println ("Current size is " + sz);
cmd = "alter table pax.xyzzy" +
" alter column column1" +
" set data type" +
" varchar(" + (sz + 50) + ")";
System.out.println ("Executing: " + cmd);
try {
Statement sttmnt = conn.createStatement();
sttmnt.execute (cmd);
} catch (Exception e) {
System.out.println ("** Warning: table alter: '" +
cmd + "': " + e);
e.printStackTrace();
}
}
try {
conn.close();
} catch (Exception e) {
System.out.println ("** Warning: DB close: " + e);
e.printStackTrace();
};
}
}
You can see from subsequent runs of this program that it's increasing the column width by 50 each time:
pax> java chgcolsz
Current size is 50
Executing: alter table pax.xyzzy alter column column1 set data type varchar(100)
pax> java chgcolsz
Current size is 100
Executing: alter table pax.xyzzy alter column column1 set data type varchar(150)
pax> java chgcolsz
Current size is 150
Executing: alter table pax.xyzzy alter column column1 set data type varchar(200)

SQL Syntax error when using SQLCommand.EndExecuteNonQuery

I'm trying to run two SQL statements (MSSQL 2005), asynchronously in a background worker. However, when I call the EndExecuteNonQuery method on the first SqlCommand I get a 'SQL syntax error near' error.
Here is my code:
try
{
SqlCommand sqlCmd = uow.DataLayer.CreateCommand() as SqlCommand;
sqlCmd.CommandText = "DELETE FROM dbo.EligibilityRecordKeyValue WHERE EligibilityRecord IN " +
"(SELECT EligibilityRecord FROM dbo.EligibilityRecord WHERE Organization = '" + map.Organization.Oid + "')";
IAsyncResult result = sqlCmd.BeginExecuteNonQuery();
while (!result.IsCompleted)
{
worker.ReportProgress(0, "Deleting existing record keys");
System.Threading.Thread.Sleep(200);
}
count = sqlCmd.EndExecuteNonQuery(result);
}
catch (SqlException ex)
{
}
catch (InvalidOperationException ex)
{
}
finally
{
worker.ReportProgress(2, String.Format("Existing {0} records keys deleted.", count));
}
try
{
SqlCommand sqlCmd = uow.DataLayer.CreateCommand() as SqlCommand;
sqlCmd.CommandText = "DELETE FROM dbo.EligibilityRecord WHERE Organization = '" + map.Organization.Oid + "'";
IAsyncResult result = sqlCmd.BeginExecuteNonQuery();
while (!result.IsCompleted)
{
worker.ReportProgress(0, "Deleting existing records");
System.Threading.Thread.Sleep(200);
}
count = sqlCmd.EndExecuteNonQuery(result);
}
catch (SqlException ex)
{
}
catch (InvalidOperationException ex)
{
}
finally
{
worker.ReportProgress(5, String.Format("Existing {0} records deleted.", count));
}
It fails on the first count = sqlCmd.EndExecuteNonQuery(result);
Ok, adding WAITFOR DELAY's to both SQL commands seems to have resolved the issue.
sqlCmd.CommandText = String.Format("WAITFOR DELAY '00:00:05'; DELETE FROM dbo.EligibilityRecordKeyValue WHERE EligibilityRecord IN " +
"(SELECT EligibilityRecord FROM dbo.EligibilityRecord WHERE Organization = '{0}')", map.Organization.Oid);
sqlCmd.CommandText = String.Format("WAITFOR DELAY '00:00:05'; DELETE FROM dbo.EligibilityRecord WHERE Organization = '{0}'", map.Organization.Oid);
Anyone know why this happens?