jdbc result set metadata: getting physical column names on aliased columns - jdbc

I'm using jdbc to execute query statements (in jruby)
# made-up example
sql = "select " +
"c.type as cartype, " +
"o.id as ownerid, " +
"o.type as ownertype " +
"from cars c " +
"inner join owners o " +
"on c.vin = o.vin"
# 'stmt' gotten with jdbc-connection.create_statement()
result_set = stmt.execute_query(sql)
meta_data = result_set.get_meta_data()
col_count = result_set.get_column_count()
I can query the various column aliases (get_column_name) and tables (get_table_name) for each column through the column indexes, but I also need the actual/physical names of the columns, un-aliased.
How do I get the physical/actual name of column, as it is defined in the schema ("ownerid" column alias is column "id", for instance)?

From tests with other database types, it looks as though this is database+driver specific. Using mysql get_column_name returns the actual/physical column name while get_column_label returns the alias. As an aside, both database types (mysql and sqlite) return the physical table name through get_table_name.

Related

Sum a List of averages in spring boot jpa query

I have this query thats return a list of averages
#Query("SELECT AVG(p.quantity) FROM Position p GROUP BY p.client.id") public List<Float> findAVGPositions();
But I want to return SUM of averages like this, but it doesn't work
#Query("SELECT SUM(averages) FROM (SELECT AVG(p.quantity) as averages FROM Position p GROUP BY p.client.id)") public Float findSumAVGPositions();
Can you help me? thanks
Unfortunately, in JPQL, nested selects are not permitted in FROM clause. They are allowed only in SELECT and WHERE.
You have two approaches available.
(1) Use findAVGPositions and calculate sum in Java
findAVGPositions().stream().reduce(0f, Float::sum);
(2) Use a native SQL query
#Query(value = "SELECT SUM(averages) " +
"FROM (SELECT AVG(p.quantity) AS averages " +
"FROM position p " +
"GROUP BY client_id) AS averages_select",
nativeQuery = true)
public Float findSumAVGPositions();
Depending on the database you use, AS averages_select alias might be needed or not (PostgreSQL requires it, even if it's not used).
Please, pay attention to use the correct names of a database table for Position entity and a database column for a foreign key client.id.
In my example, I assumed a standard mapping convention: position as a table name, and client_id as a foreign key column.

Syntax Error in query expression with vb 6.0

sql = "update Attendance set Attended=Attended+1 where Student ID like 15001"
db.Execute (sql)
is is showing :
"syntax error(missing operator) in query expression 'Student ID like
15001'
If realy you have a space between Student and ID tehn your query must be :
sql = "update Attendance set Attended=Attended+1 where [Student ID] like 15001"
db.Execute (sql)
sql should always be written with an _. For Example Student ID should always be Student_ID so that it has the idea of reading which column it needs to filter its search. For future purposes always create a column name with an _.
sql = "update Attendance set Attended=Attended+1 where Student_ID like 15001"
db.Execute (sql)
or
sql = "update Attendance set Attended=Attended+1 where [Student ID] like 15001"
db.Execute (sql)
Try something that looks a bit cleaner...
sql = "Update tblAttendance SET "
sql = sql & " Attended = Attended + 1 "
sql = sql & " Where Student_ID = 15001 "
db.execute SQL <-- no paranthesis

simple join syntax not properly working

I'd like to show the number of records in the history table grouped by name of service
service(code,name)
history(id, code,....)
Please note that there is no relationship between the two table history and service, history stores the activity independently from the other tables
I have tested this sql query and it returns the expected result:
select s.name, count(*) from history c
join service s
on c.code=s.code
where c.state='INITIALE'
group by s.name
Actually, I'd like to write it in jpql, I did alike
Query query =entityManager.createQuery(" select s.name, count(*) from ServiceEntity s join"
+ " HistoryEntity c "
+ " where c.code=s.code and c.state='INITIALE'"
+ " group by c.name order by c.name"
);
I got this error : Path expected for join!....
Invalid path: 'c.code'....right-hand operand of a binary operator was null....unexpected end of subtree
Try this
Query query = entityManager.createQuery("select s.name, count(s) from ServiceEntity s, HistoryEntity c "
+ " where c.code = s.code and c.state = 'INITIALE'"
+ " group by s.name order by s.name"
);

Update Datetime Values in all the Tables in the database

How can I update all the tables which have Datetime fields in a database?
Eg. My DB has 50 Tables which has a column in the 50 tables which is of DATETIME Type.
I need to update the Column of datetime type with a new value.
How can I write a generic query to update datetime column in all the tables in the DB with a new value of datetime?
While I question the value of this in an unprecedented way (you should be proud!), you can't write a generic query that does this without dynamic SQL.
DECLARE
#sql NVARCHAR(MAX) = N'',
#newDateTime DATETIME = '20131217 07:30';
SELECT #sql += N'
UPDATE ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name)
+ ' SET ' + QUOTENAME(c.name) + ' = #newDateTime;'
FROM sys.columns AS c
INNER JOIN sys.tables AS t ON c.[object_id] = t.[object_id]
INNER JOIN sys.schemas AS s ON t.[schema_id] = s.[schema_id]
WHERE c.system_type_id = 61;
EXEC sp_executesql #sql, N'#newDateTime DATETIME', #newDateTime;

Fetch dates (by month or year) stored in TIMESTAMP using JPA

I am facing a problem and I would like you to help me.
It turns out I have one table in my Oracle 11g database where I store failures of one electronic device. The table definition is following:
CREATE TABLE failure
( failure_id NUMERIC NOT NULL
, fecha TIMESTAMP NOT NULL
, module_id NUMERIC NOT NULL
, code NUMERIC
, PRIMARY KEY(failure_id)
);
Where 'fecha' means 'date'.
I need to fetch failures by YEAR or by MONTH for one specific module but I can't. My ORM maps the TIMESTAMP type to java.sql.Date but I don't know how to compare the month in the JPQL sentence. I have tried to use ORACLE functions with native queries but I front with another issue: to cast the results.
I am using JPA 2.0 with Eclipselink 2.3.2.
My doubts are:
Can I use Oracle functions with this version of Eclipselink library? My experience say no.
Query query = entityManager.createQuery("SELECT f FROM Failure f "
+ "WHERE EXTRACT(YEAR FROM f.fecha) = ?1 "
+ "AND f.moduleId.moduleId = ?2");
query.setParameter(1, year);
query.setParameter(2, idModule);
I get this error: Unexpected token [(]
Can I use Eclipselink functions? My experience say no.
Query query = entityManager.createQuery("SELECT f FROM Failure f "
+ "WHERE EXTRACT('YEAR', f.fecha) = ?1 "
+ "AND f.moduleId.moduleId = ?2");
query.setParameter(1, year);
query.setParameter(2, idModule);
Same error.
Do you know a simple way to fetch this data using only one query?
I know I can fetch one module and then check failures with loops but I think it is not the best performing solution.
Thanks.
My sources:
Eclipselink JPA functions link
Eclipselink Query Enhancements link
A native query is written in the SQL dialect of your DB so can use DB specific functionality see the createNativeQuery methods of the EntityManager.
However there is another solution, test the timestamp against a lower and upper value:
WHERE f.fecha >= '2012-9-1' AND f.fecha < '2012-10-1'
The syntax in EclipseLink 2.4 for EXTRACT is,
EXTRACT(YEAR, f.fecha)
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#Functions
I used Eclipselink v 2.4 functions and I am getting values using this:
Query query = entityManager.createQuery("SELECT f FROM Failure f "
+ "WHERE SQL('EXTRACT (YEAR FROM ?)', f.fecha) = ?1 "
+ "AND f.moduleId.moduleId = ?2 ");
Extracting year from date stored in database avoids to me one comparison between two dates.
Use
Query query = entityManager.createQuery("SELECT f FROM Failure f "
+ "WHERE EXTRACT(YEAR from f.fecha) = ?1 "
+ "AND f.moduleId.moduleId = ?2");
I was facing the same problem. I only checked for the correct syntax of that EXTRACT function for oracle and it worked for me! (Notice the FROM clause into the function syntax.
#NamedQuery(name = "Registros.findByFechacaptura", query = "SELECT s FROM Registros s WHERE EXTRACT(YEAR FROM s.fechacaptura) = EXTRACT(YEAR FROM :fechacaptura)")

Resources