Unable to solve uncategorized SQLException when calling SQL Server using JDBC - java

I am using JDBCTemplate to query a SQL server using:
List results = jdbc.query(statement, new ResultDataMapper());
I have tried the statement in PreparedStatementCreator and String formats but neither work. I received the exception below:
SQL state [null]; error code [0]; The statement did not return a result set.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
My sql is:
IF OBJECT_ID('tempdb.dbo.#tempSearch', 'U') IS NOT NULL
DROP TABLE #tempSearch;
CREATE TABLE #tempSearch
(
ID int,
Value VARCHAR(255)
)
INSERT INTO #tempSearch
VALUES(1,'?'),
(2,'?');
with cte as (
select RoleID,','+replace(replace(GroupNames,',',',,'),' ','')+',' GroupNames from UserGroup_Role_Mapping
)
,cte2 as(
select cte.RoleID, replace(cte.GroupNames,','+Value+',','') as GroupNames, s.ID, s.Value
from cte
join #tempSearch s on ID=1
union all
select cte2.RoleID, replace(cte2.GroupNames,','+s.Value+',','') as l, s.ID ,s.Value
from cte2
join #tempSearch s on s.ID=cte2.ID+1
)
SELECT a.Role, a.Sort_Order, a.Parent, a.Parent_ID, a.Parent_URL, a.Child, a.Child_ID,a.Child_URL
FROM NC_View a
WHERE a.Role IN (
Select Name from (
Select distinct RoleID from cte2 where len(GroupNames)=0
) tempRoles
join User_Role
on tempRoles.RoleID = User_Role.ID
)
DROP TABLE #tempSearch
I know the SQL works fine but i just cant get over the hump of calling it from JDBC. I have the Mapper and extractor all done too.
I ran this with a PreparedStatementCreator and String:
when i use PreparedstatementCreator and try to set 2 variables I get index out range errors "com.microsoft.sqlserver.jdbc.SQLServerException: The index 1 is out of range.":
PreparedStatementCreator returnValue = new PreparedStatementCreator() {
#Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
sql.append("("+x +",'" + "?" +"'),"); //when constructing the sql
PreparedStatement statement = con.prepareStatement(sql.toString());
statement.setString(z++, group); //when setting those values
I am not sure why this is? is the syntax incorrect? It seems it is not detecting the set?
from debug i also see:
Unable to translate SQLException with Error code '0'
If I use String straight out i get:
org.springframework.jdbc.UncategorizedSQLException: StatementCallback; uncategorized SQLException for SQL [
SQL FROM ABOVE - I TESTED AND IT WORKS
]; SQL state [null]; error code [0]; The statement did not return a result set.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
I am not sure if the SQL is too complex or what. But also confused how using PreparedStatementCreator it wasnt detecting the ? to set variables... I am running out of ideas. I tried Multiqueries=true too
If I use SET NOCOUNT ON i get a different error:
Unable to solve uncategorized SQLException when calling SQL Server using JDBC
So i am bit confused too. I am not inserting a lot of data so maybe it doesn't matter?
Thanks!

Related

DB2 Query issue with Hibernate when checking for values

I have this query, using Hibernate 4 and DB2, running a native query:
select * from TABLE1 t where (:param1 is null or t.NAME = :param1)
That throws exception that null is invalid in the context (since SQL becomes select * from TABLE1 t where (null is null or t.NAME = null))
So I tried:
select * from TABLE1 t where (COALESCE(:param1,'!') = '!' or t.NAME = :param1)
That throws exception when I pass value "JUSTIN" -
"THE VALUE OF INPUT VARIABLE OR PARAMETER NUMBER IS INVALID OR TOO LARGE FOR THE TARGET COLUMN OR THE TARGET VALUE"
Which appears to be cause by the fact that DB2 checks the length of ":param1" against "!".
Is there a way in DB2 to pass dynamic parameters?
I'm starting to hate DB2....
Turns out this works with Hibernate:
select * from TABLE1 t where NVL(:param1, t.NAME) = t.NAME;

Informix java.sql.SQLException: Column (...) not found in any table in the query (or SLV is undefined)

The query below is working without any problems in my java based sql Editor:
begin work;
create SEQUENCE if not exists zahlpaketcounter start 1;
select zahlpaketcounter.nextval as counter,*
from (
SELECT
firma_nr
,zahlpaket.nummer
,zahlpaket.bezeichnung
,personenkonto.kontonummer
,personenkonto.bezeichnung
,zahlbewegung.op_nr
,zahlbewegung.zahlbetrag_druck
,fibu_beleg.archiv_nr
FROM integris.zahlbewegung
join zahlpaket on zahlbewegung.zahlpaket_id=zahlpaket.zahlpaket_id
join integris.personenkonto on zahlbewegung.personenkonto_id=personenkonto.personenkonto_id
join integris.opbewegung on zahlbewegung.opbewegung_id=opbewegung.opbewegung_id
join integris.fibu_beleg on opbewegung.fibu_beleg_id=fibu_beleg.fibu_beleg_id
join integris.firma on zahlpaket.firma_id = firma.firma_id
where 1=1
and zahlbewegung.zahlbetrag_druck >=0
order by nummer,personenkonto.kontonummer,zahlbewegung.op_nr
);
drop sequence zahlpaketcounter;
commit work;
when I use in it java:
sql=getTextResource(this,"sql/getZahlläufe.sql");
fibustmt.execute(sql);
the execute method fails with:
java.sql.SQLException: Column (zahlpaketcounter) not found in any table in the query (or SLV is undefined).
Why? Any Ideas?
Seems not possible to use multiple statements with execute(). You should use addBatch() and executeBatch() but not with a SELECT.
It works with 3 execute().
String sqlQ="create SEQUENCE if not exists zahlpaketcounter start 1";
PreparedStatement pstmt = cnx.prepareStatement();
pstmt.execute();
sqlQ="SELECT ...";
pstmt = cnx.prepareStatement();
pstmt.execute();
sqlQ="drop SEQUENCE if exists zahlpaketcounter";
pstmt = cnx.prepareStatement();
pstmt.execute();

JDBC: Create table query syntax error

I am trying to execute a create query using JDBC. I have a method which creates the query and then I execute it but its showing me syntax error. Below is the stack trace :
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'supplierId varchar,supplierUrl varchar,totalActivities varchar,activityName varc' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2941)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1623)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1715)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3243)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1343)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1260)
Now the query generated is this :
create table demo ( ID INTEGER PRIMARY KEY AUTO_INCREMENT,supplierName varchar,supplierId varchar,supplierUrl varchar,totalActivities varchar,activityName varchar,activityPrice varchar,tourCode varchar,starRating varchar,totalReviews varchar,geography varchar,duration varchar,category varchar,subCategory varchar);
And below is the method which is generating this query :
private static String getCreateTableQuery(String tableName, String columnData) {
StringBuilder sqlStatement = new StringBuilder("");
sqlStatement.append("create table " + tableName + " ( ID INTEGER PRIMARY KEY AUTO_INCREMENT,");
String[] columns = columnData.split(">"); // columns are separated by >
for (int i = 0; i < columns.length; i++) {
sqlStatement.append(columns[i] + " varchar");
if (i != columns.length - 1) { // no commas after last column
sqlStatement.append(",");
}
}
sqlStatement.append(");");
return sqlStatement.toString();
}
And this is how am executing the query :
SessionImpl sessionImpl = (SessionImpl) getSessionFactory().openSession();
Connection conn = (Connection) sessionImpl.connection();
Statement statement = (Statement) conn.createStatement();
statement.executeUpdate(query);
sessionImpl.close();
conn.close();
Am unable to understand the syntax error. Can someone please explain?
I think you have to pass max length for varchar fields:
Please check this your query will be like that:
create table demo ( ID INTEGER PRIMARY KEY AUTO_INCREMENT,supplierName varchar(255),supplierId varchar(255),supplierUrl varchar(255),totalActivities varchar(255),activityName varchar(255),activityPrice varchar(255),tourCode varchar(255),starRating varchar(255),totalReviews varchar(255),geography varchar(255),duration varchar(255),category varchar(255),subCategory varchar(255));
Here is insert Query:
insert into demo
( supplierName, supplierId, supplierUrl, totalActivities, activityName,
activityPrice, tourCode, starRating, totalReviews, geography, duration,
category, subCategory)
values
(supplierName, supplierId, supplierUrl, totalActivities, activityName,
activityPrice, tourCode, starRating, totalReviews, geography, duration,
category, subCategory)
In Mysql you need to define a length to the varchar. Take a look here:
Why does VARCHAR need length specification?
I don't see a problem with your Java code. Fix your create table statement and you'll probably be fine.

Spring JDBCTemplate throwing BadSqlGrammarException

I have an SQL query that is executed using Spring JDBCTemplate to retrieve data from an Oracle DB. While executing the statement, org.springframework.jdbc.BadSqlGrammarException is thrown.
The same SQL statement returns proper results when run in the SQL Plus console.
Below is the code that I am trying to execute:
String query = "SELECT DISTINCT O.ORGID FROM ORGANISATIONS O WHERE O.ORGTYPE NOT IN ('P','G') AND O.USERID = 40";
ArrayList<Organisations> orgsList = new ArrayList<Organisations>();
Object[] paramsArray = new Object[]{};
orgsList = (ArrayList<Organisations>) getJdbcTemplate().query(query.toString(), paramsArray ,
new RowMapper<Organisations>(){
public MetricsRoleMap mapRow(ResultSet rs, int rowNum) throws SQLException {
// Data retrieval code;
};
});
Here is the error generated:
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [ SELECT DISTINCT O.ORGID FROM ORGANISATIONS O WHERE O.ORGTYPE NOT IN ('P','G') AND O.USERID = 40]; nested exception is java.sql.SQLException: Invalid column name
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231) [spring-jdbc-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73) [spring-jdbc-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:660) [spring-jdbc-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:695) [spring-jdbc-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:727) [spring-jdbc-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:737) [spring-jdbc-4.0.5.RELEASE.jar:4.0.5.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:787) [spring-jdbc-4.0.5.RELEASE.jar:4.0.5.RELEASE]
Similar code that I wrote for another method works well. I think there is a minor mistake here, but I am unable to find it.

JdbcTemplate problems with nested queries

I'm trying to use nested queries with JdbcTemplate but found the issue, it seems to me that it's doesn't suppot nested queries.. Am i right? or what i need to change?
So, i invoke
getJdbcTemplate().query(request, new Object[]{name}...)
// request is query which you can see in error message
which gives results in oracle but failes with
org.springframework.jdbc.InvalidResultSetAccessException: PreparedStatementCallback; invalid ResultSet access for SQL [select sq.name as name from (select t1.name as name from table1 t1 left outer join table2 t2 on t2.id = t1.fk_id where t1.name is not null ) sq where upper(name) like upper('?')]; nested exception is java.sql.SQLException: Invalid column index
EDITED
request is a simple String object which is actually an sql that you see in exception message. The eturn object has no matter in this situation as i left it empty (for testing ourpose)
but just for you to be sure here it is:
List<MyObject> list = getJdbcTemplate().query(request, new Object[]{"Somename"}, new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
return new MyObject();
}
});
Try changing the upper('?') to upper(?). By putting the ? in quotes, the database doesn't realize that you're dealing with a parameter.

Categories

Resources