I get a column not found exception even if the column exists - java

I want to execute a query against a MySQL database with Java. The code looks like this:
ResultSet resultSet = statement.executeQuery("select col1 from tb1 inner join tb2 on tb1.col2 = tb2.col3 where col4='"+foo+"'");
The query works perfectly when I use the shell but it doesn't work when I run it with Java because it says that col4 doesn't exist. But col4 exists.
I've just tried something like this;
select col1 from dbname.tb1 as a inner join dbname.tb2 as b on a.col2 = b.col3 where b.col4 = 'foo'

You should call the col4 with the table prefix "tb1" or "tb2".
As example:
select tb1.col1 from tb1 inner join tb2 on tb1.col2 = tb2.col3 where tb1.col4=...

The problem was not there. It was I little bit further:
ResultSet resultSet = statement.executeQuery("select col1 from tb1 inner join tb2 on tb1.col2 = tb2.col3 where col4='"+foo+"'");
myarray.add(resultSet.getString("col4"));//col4 can't exist here because it has not been selected
After executing the query I wanted to access a column that hadn't been selected.

Related

JQPL select inside select

just switched to spring boot from .NET Core, in .NET core we can easily nest a select inside a select like this:
var result = from c in context.Cars
join br in context.Brands
on c.BrandId equals br.Id
join col in context.Colors
on c.ColorId equals col.Id
select new CarDetailDto
{
Id = c.Id,
BrandName = br.Name,
CarName = c.Name,
ColorName = col.Name,
DailyPrice = c.DailyPrice,
ModelYear = c.ModelYear,
CarImages = (from cimg in context.CarImages
where cimg.CarId == c.Id
select new CarImage
{
Id = cimg.Id,
ImagePath = cimg.ImagePath,
CarId = c.Id,
Date = cimg.Date
}).ToList()
};
I want to do that in JPQL as well but didnt manage to solve
#Query( select column1, column2, column3 from tablename1 where coluname=(select columname from tablename2 where columnname=abcd) )
Your JPQL query should look like above.
Whatever subquery you write with condition.
If your query is fetching 3 column you need to create a DTO with same column name.
If your query is fetching list of rows then your actual jpql will look like this.
#Query( select column1, column2, column3 from tablename1 where coluname=
(select columname from tablename2 where columnname=abcd) )
List<ResultDTO> findAllResultList(Parameter value);
Above it is mapping the result to list of DTO objects to result rows.
If your query is fetching single row then your actual jpql will look like this.
#Query( select column1, column2, column3 from tablename1 where coluname=
(select columname from tablename2 where columnname=abcd) )
ResultDTO findResult(Parameter value);
The single result is mapped to one DTO object.
Make sure your result column name and DTO column name matches
Using the JPA repository call the names of the method which you used for the particular query.

db2 sqlstate 42972 error

I am getting this error when I am trying to execute this sql query
INSERT INTO
AGG_QUALITY
SELECT
QIF.DATEDM_ID,
'Status' AS BREAKDOWN_TYPE,
HCR.VALUE,
QIF.SCANDEFINITION_ID,
QIF.QUALITYISSUE_VALUE,
COUNT(QIF.QUALITYISSUEFACT_ID),
COUNT(QRF.QUALITYRESOLUTIONFACT_ID)
FROM
QUALITYISSUEFACT QIF,
HUBCODERECORD HCR,
ITEMSTATUS ITS
LEFT JOIN
QUALITYRESOLUTIONFACT QRF
ON
QIF.QUALITYISSUEFACT_ID = QRF.QUALITYISSUEFACT_ID
WHERE
QIF.DATEDM_ID > startDateDMId
AND QIF.DATEDM_ID <= endDateDMId
AND HCR.CODE = ITS.H_STATUS_TYPE
AND QIF.DIMENSION_ROM_PK = ITS.ITEMMASTER_ID
GROUP BY
QIF.DATEDM_ID, HCR.VALUE, QIF.SCANDEFINITION_ID, QIF.QUALITYISSUE_VALUE
;
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0338N An ON clause associated with a JOIN operator or in a MERGE statement
is not valid. LINE NUMBER=31. SQLSTATE=42972
Try like below with inner joins:
INSERT INTO
AGG_QUALITY
SELECT
QIF.DATEDM_ID,
'Status' AS BREAKDOWN_TYPE,
HCR.VALUE,
QIF.SCANDEFINITION_ID,
QIF.QUALITYISSUE_VALUE,
COUNT(QIF.QUALITYISSUEFACT_ID),
COUNT(QRF.QUALITYRESOLUTIONFACT_ID)
FROM
QUALITYISSUEFACT QIF
INNER JOIN
HUBCODERECORD HCR
ON QIF.DIMENSION_ROM_PK = ITS.ITEMMASTER_ID
INNER JOIN
ITEMSTATUS ITS
ON QIF.DIMENSION_ROM_PK = ITS.ITEMMASTER_ID
LEFT JOIN
QUALITYRESOLUTIONFACT QRF
ON
QIF.QUALITYISSUEFACT_ID = QRF.QUALITYISSUEFACT_ID
WHERE
QIF.DATEDM_ID > startDateDMId
AND QIF.DATEDM_ID <= endDateDMId
GROUP BY
QIF.DATEDM_ID, HCR.VALUE, QIF.SCANDEFINITION_ID, QIF.QUALITYISSUE_VALUE
;
see if it helps
Had the same error here. (note, my Table1 has NO rows)
On my side I could solve it by changing the additional (comma separated) table2 to a REAL inner join.
Example from
select xxx from Table1 t1, Table2 t2
where (t2.col1 = t1.col1) and (t1.col2 = "whatever")
to
select xxx from Table1 t1
INNER JOIN Table2 t2 ON (t2.col1 = t1.col1)
where (t1.col2 = "whatever")
Hope this helps someone else.
(problem occured on DB2 9.7)

UNION in MySQL using JDBC

I have problem when using UNION problem: I have 2 tables TOPIK and SUBTOPIK which I do left join and right join then make union of them using the following statement:
mySqlStmt = "SELECT *
FROM TOPIK
LEFT OUTER JOIN SUBTOPIK
ON TOPIK.IDTOPIK=SUBTOPIK.IDTOPIK
WHERE (TOPIK.TARGETNPMHS LIKE '%0000312100006%'
OR ((TOPIK.TARGETOBJECTNICKNAME LIKE '%OPERATOR KEPALA BAA%'
OR TOPIK.TARGETOBJECTNICKNAME LIKE '%OPERATOR BAA%' )
AND TOPIK.TARGETNPMHS IS NULL))
UNION
SELECT *
FROM TOPIK
RIGHT OUTER JOIN SUBTOPIK
ON TOPIK.IDTOPIK=SUBTOPIK.IDTOPIK
WHERE (SUBTOPIK.NPMHSRECEIVER LIKE '%0000312100006%'
OR ((SUBTOPIK.OBJNICKNAMERECEIVER LIKE '%OPERATOR KEPALA BAA%'
OR SUBTOPIK.OBJNICKNAMERECEIVER LIKE '%OPERATOR BAA%' )
AND SUBTOPIK.NPMHSRECEIVER IS NULL))"
The code above works on mysql workbench, but when i use it in java,
get connection...bla..bla;
stmt = con.prepareStatement("mySqlStmt");
rs = stmt.executeQuery();
while(rs.next()) {
String topik_idTopik = ""+rs.getLong("TOPIK.IDTOPIK");
}
i got
java.sql.SQLException: Column 'TOPIK.IDTOPIK' not found.
but both TOPIK and SUBTOPIK have this column.
The column's alias is IDTOPIK, you should not use the fully qualified name:
stmt = con.prepareStatement(mySqlStmt);
rs = stmt.executeQuery();
while(rs.next()) {
String topik_idTopik = ""+rs.getLong("IDTOPIK");
}
Your where clause undoes the right outer join. You might as well do:
SELECT *
FROM TOPIK t LEFTJOIN
SUBTOPIK s
ON t.IDTOPIK = s.IDTOPIK
WHERE (s.NPMHSRECEIVER LIKE '%0000312100006%' OR
(s.OBJNICKNAMERECEIVER LIKE '%OPERATOR KEPALA BAA%' OR
s.OBJNICKNAMERECEIVER LIKE '%OPERATOR BAA%'
) AND
s.NPMHSRECEIVER IS NULL
)
);
Of course, the problem you have is with the alias, not the join, but you might as well have a correct query.

Invalid operation for read only resultset: updateString

Following is my code(Re-constructed) which select & update STATUS field depending upon the conditions. (Using Servlets, Oracle as Backend and JDBC driver)
ResultSet rs=null;
String query = "select A.NAME, A.ADDRESS, A.STATUS, B.CLASS from TABLE_ONE A, TABLE_TWO B where A.STATUS='N'";
pstmt = con.prepareStatement(query,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = pstmt.executeQuery();
while(rs.next())
{
String name = rs.getString("NAME");
String address = rs.getString("ADDRESS");
String class = rs.getString("CLASS");
String msg = //Other statements to check what status to be set
if(msg.equals("OK"))
rs.updateString("STATUS", "S");
else
rs.updateString("STATUS", "E");
rs.updateRow();
}
I am getting the error while updating:
java.sql.SQLException: Invalid operation for read only resultset: updateString
Any suggestions will be appreciated.
Update 1:
The same code was working when select statement was selecting data from single table, so is there any issue when selecting data from two tables in single query?
[Note: As #javaBeginner has mentioned in comments it will work only for one table.]
The following limitations are placed on queries for enhanced result sets. Failure to follow these guidelines will result in the JDBC driver choosing an alternative result set type or concurrency type.
To produce an updatable result set (from specification):
A query can select from only a single table and cannot contain any join operations.
In addition, for inserts to be feasible, the query must select all non-nullable columns and all columns that do not have a default value.
* A query cannot use "SELECT * ". (But see the workaround below.)
* A query must select table columns only. It cannot select derived columns or aggregates such as the SUM or MAX of a set of columns.
To produce a scroll-sensitive result set:
A query cannot use "SELECT * ". (But see the workaround below.)
A query can select from only a single table.
Try This :
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
//Execute a query
String sql = "select A.NAME, A.ADDRESS, A.STATUS, B.CLASS from TABLE_ONE A, TABLE_TWO B where A.STATUS='N'";
ResultSet rs = stmt.executeQuery(sql);
//Extract data from result set
rs.beforeFirst();
while(rs.next())
{
String name = rs.getString("NAME");
String address = rs.getString("ADDRESS");
String class = rs.getString("CLASS");
String msg = //Other statements to check what status to be set
if(msg.equals("OK"))
rs.updateString("STATUS", "S");
else
rs.updateString("STATUS", "E");
rs.updateRow();
}
Just changed Prepared statement to create statement
SELECT * makes the resultSet readonly. SELECT COLUMN_NAME makes it updatable.
So instead of SELECT * FROM TABLE use SELECT COLUMN1, COLUMN2, ... FROM TABLE.

Jave SQL executeQuery throws up error for valid sql statement

I am using java java.sql.* for querying from SQLite DB. I found a starnge issue where I write a sqlString as:
SELECT n.Name as Name,
c.Value as Value0,
d.Value as Value1
FROM (Table1 c inner join Table2 n on c.NameID = n.ID),
Table3 d
WHERE c.RunID = 1
and d.RunID = 2
and c.NameID = d.NameID
The statement stmt.executeQuery(sqlQuery) throws the following exception:
java.sql.SQLException: no such column: n.Name
at org.sqlite.DB.throwex(DB.java:288)
at org.sqlite.NativeDB.prepare(Native Method)
at org.sqlite.DB.prepare(DB.java:114)
at org.sqlite.Stmt.executeQuery(Stmt.java:89).............
Name is already part of the Table2 table. The same statement is working fine from SQLite command prompt. But when I remove the open brackets and try to execute from java, there is no problem. Any idea why this happens so?
Try something like this, use sub resultset
SELECT rs1.Name AS NAME,
rs1.Value0 AS Value0,
d.Value AS Value1
FROM (SELECT n.Name AS NAME,
c.Value AS Value0,
d.Value AS Value1
FROM Table1 c INNER JOIN Table2 n ON c.NameID = n.ID) rs1,
Table3 d
WHERE c.RunID = 1
AND d.RunID = 2
AND c.NameID = d.NameID
The variables used in inner queries could not be referred outside. For example, you have used the variable n in inner sql. But you are referring it outside. The variable n is out of it's scope there.
Hi Friends Thanks for your fast responses. I am able to solve this problem. I am sharing this so if any1 else get this problem can do this:
SELECT ABC.Name as Name, ABC.Value as Value0, d.Value as Value1
FROM
(select n.Name as Name, c.Value as Value0 from Table1 c
inner join Table2 n on c.NameID = n.ID) AS ABC,
Table3 d ......;
Regards,Tor

Categories

Resources