java.lang.IllegalArgumentException: Unknown column name 'mobile' in table account_metric_usage - java

The column "mobile" does indeed exists in my table. I am running mySQL database version 5.8+
Here is my java code that throws the exception:
Where query =
dao.queryBuilder().selectColumns("mobile").where().eq(ACCOUNT,
account).and().ge(DATE, startStamp).and().le(DATE, endStamp);
the selectColumns only takes strings or iterator
If i run the query below on my database. i get the desired results:
SELECT mobile FROM account_profile_metric_usage WHERE ((account = 'qa23-redis-smoke' AND date >= '2017-01-28' ) AND date <= '2017-02-27' )
If i run the query below it fails to return the results since mobile is in quotes. Which is not what i want.
SELECT 'mobile' FROM account_profile_metric_usage WHERE ((account = 'qa23-redis-smoke' AND date >= '2017-01-28' ) AND date <= '2017-02-27' )
I need to be able to run the first SQL query in ormLite. mobile is of type bigInt

Related

Postgres overlapping symbol not running in java

I have a query to test two dates against two timestamp columns in the table if they overlap or not.
Query is working fine in the database client but when i added it in my java code it fails with an exception error.
I need to know how to format the && symbols in the query to be able to work.
SELECT count(*)
FROM attendance_jobs
WHERE tsrange( start_date, end_date) && tsrange(TIMESTAMP '2019-04-22', TIMESTAMP '2019-03-22 ')
Here is my java code:
long count = jdbi.withHandle(handle -> {
return handle.createQuery("select count(*) from attendance_jobs where tsrange(start_date, end_date) && tsrange(timestamp :start_date, timestamp :end_date)")
.bind("start_date", start_date)
.bind("end_date", end_date)
.mapTo(Long.class)
.findOnly();
});
The start_date and end_date data type is Timestamp.
org.jdbi.v3.core.statement.UnableToExecuteStatementException: org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
This is just guesswork, but I think you should have a look at the usage of :start_date and :end_date again:
If start_date and end_date (java variables) are of type Timestamp you should remove the timestamp prefix to :start_date and :end_date in the query. As the documentation says, the java type Timestamp is supported by jdbi:
Out of the box, Jdbi supports the following types as SQL statement arguments:
* ...
* java.sql: Blob, Clob, Date, Time, and Timestamp
* ...
So my guess is that you have to use the query like this:
long count = jdbi.withHandle(handle -> {
return handle.createQuery("select count(*) from attendance_jobs where tsrange(start_date, end_date) && tsrange(:start_date, :end_date)")
.bind("start_date", start_date)
.bind("end_date", end_date)
.mapTo(Long.class)
.findOnly();
});
Also, but this may be personal taste, I recommend to use different spelling of bind variables and database columns. The latter with underscores (as you did), the other in camel case so it is less confusing if you use similar names. Also, it is uncommon to use underscores in java variables, so the code would look similar to this in my spelling:
Timestamp startDate = ...;
Timestamp endDate = ...;
String queryString = "select count(*) from attendance_jobs "
+ "where tsrange(start_date, end_date) && tsrange(:startDate, :endDate)";
long count = jdbi.withHandle(handle -> {
return handle.createQuery(queryString)
.bind("startDate", startDate)
.bind("endDate", endDate)
.mapTo(Long.class)
.findOnly();
});

Pessimistic Lock while executing paginable query

tl;dr How to write following query:
SELECT * FROM T_BATCH_DATA WHERE ID IN (SELECT ID FROM T_BATCH_DATA OFFSET 5 ROWS FETCH FIRST 10 ROWS ONLY) FOR UPDATE ; using JPQL?
I have a JPQL named query: name=Foo.foo, query = "FROM Foo foo WHERE foo.modified<:date"
which is supposed to retrieve paginated results and set lock to prevent concurrent reading by another POD. Below is the corresponding code:
findFooByLastInteractionUpdate(int pageIndex, int noOfRecords, LocalDateTime retentionDate)
{
return entityManager.createNamedQuery("Foo.foo", Foo.class)
.setParameter("date", date) //
.setFirstResult(pageIndex * noOfRecords) //
.setMaxResults(noOfRecords) //
.setLockMode(LockModeType.PESSIMISTIC_WRITE) //
.getResultList();
}
The unit test is extremally simple and looks like this:
// given:
initializeDb();
LocalDateTime date = ...;
// when:
List<Foo> result = cut.findFooByLastInteractionUpdate(0, 3, date);
// then:
Assert.assertEquals(2, result.size());
And initialization method looks like this:
initializeDb() {
getEntityManager().createNativeQuery("INSERT INTO FOO (ID, ..., ..., ...) VALUES (1, ..., ..., ...)").executeUpdate();
}
However, when I execute this query the resulting logs are:
javax.persistence.PessimisticLockException: Exception [EclipseLink-4002 (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.h2.jdbc.JdbcSQLException:
Syntax error in SQL statement ... FROM FOO WHERE (MODIFIED < ?) FOR UPDATE LIMIT[*] ? OFFSET ? ";
SQL statement: SELECT FOO ... FROM FOO WHERE (MODIFIED < ?) FOR UPDATE LIMIT ? OFFSET ? [42000-196]
Error Code: 42000
In H2 manual i found that 42000 code corresponds to syntax error.
Having access only to Oracle DB i tried to execute similar query by hand so:
SELECT * FROM FOO FOR UPDATE FETCH FIRST 10 ROWS ONLY OFFSET 5 ROWS;
which results in ORA-02014.
However I managed to rewrite the query in a way that executes successfully:
SELECT * FROM T_BATCH_DATA WHERE ID IN (SELECT ID FROM T_BATCH_DATA OFFSET 5 ROWS FETCH FIRST 10 ROWS ONLY) FOR UPDATE ;
How can I rewrite the JPQL query?

PreparedStatement.executeUpdate() is not working for Oracle

I am using PreparedStatement for executing the update query.
The following is the query:
String callersUpdateQuery = "update W67U999S a set pcrdattim= ? where exists (select b.CRDATTIM, b.RECORDCD, b.CRNODE, b.UNITCD, b.WRKTYPE from W03U999S b where a.PCRDATTIM = ? and a.CCRDATTIM = b.CRDATTIM and a.CRECORDCD = b.RECORDCD and a.CCRNODE = b.CRNODE and a.PRECORDCD = 'F' and a.PCRNODE = '01' and b.WRKTYPE = 'CALLER' and b.UNITCD=? and a.crecordcd='T')";
The below is the java code that should update the records:
preparedStatement = dbConnection.prepareStatement(callersUpdateQuery);
preparedStatement.setString(1,newFolderCrdattim);
preparedStatement.setString(2,crdattim);
preparedStatement.setString(3,businessAreaName.trim());
int j = preparedStatement.executeUpdate();
But preparedStatement.executeUpdate() is not updating the required rows and returning the updated rows count as zero. Weirdly, the same sql query when I execute at the database end, the records are getting updated.
My database is Oracle and the schema of the table that should be updated is below:
Name Null Type
----------- -------- ----------
PCRDATTIM NOT NULL CHAR(26)
PRECORDCD NOT NULL CHAR(1)
PCRNODE NOT NULL CHAR(2)
RECORDTYPE NOT NULL NUMBER(3)
CCRDATTIM NOT NULL CHAR(26)
CRECORDCD NOT NULL CHAR(1)
CCRNODE NOT NULL CHAR(2)
CRDATTIM NOT NULL CHAR(26)
LINKRULE_ID NOT NULL NUMBER(14)
Can anyone guess what's wrong with the code or query?
First, did you check for existence of tuples on the select you're using as condition in where clause?
If there are rows being returned. The issue may be related to the transaction in which you're executing your update statement. Double check for your transaction mode and if it is really being committed.
As a query optimization suggestion I'd change the statement to:
String callersUpdateQuery =
"update W67U999S a
set pcrdattim= ?
where
a.PCRDATTIM = ?
and a.PRECORDCD = 'F'
and a.PCRNODE = '01'
and a.CRECORDCD ='T'
and exists (
select
b.CRDATTIM,
b.RECORDCD,
b.CRNODE,
b.WRKTYPE
from W03U999S b
where
b.CCRDATTIM = a.CRDATTIM
and b.CRECORDCD = a.RECORDCD
and b.CCRNODE = a.CRNODE
and b.WRKTYPE = 'CALLER'
and b.UNITCD=?
)";
That way you will be first reducing the tuples from a then use it to narrow the b tuples only to those that match.
Oracle CHAR type is the culprit here. The columns that I want to update are of type CHAR. That's causing the issue. This link helped me in figuring out the solution: Oracle JDBC and Oracle CHAR data type

'select' preparedStatement wih Timestamp returns always empty RecordSet

I try to retrieve records from ORACLE database table using JDBC thin driver.
The prepared statement I'm using:
(1)
SELECT (t1.LOGGED_TIME - ?) AS TDIFF, t1.ID, t1.STATUS, t1.LOGGED_TIME, t1.SERVER_TIME
FROM table_1 t1
WHERE (
((t1.LOGGED_TIME - ?) <= INTERVAL '10' DAY)
AND ((t1.LOGGED_TIME - ?) >= INTERVAL '-10' DAY))
ORDER BY t1.LOGGED_TIME DESC
where t1.LOGGED_TIME represents a timestamp column. Every three parameters are identical timestamps set with
java.sql.Timestamp controlTime = Timestamp.valueOf("2014-08-15 03:52:00");
lookupTime.setTimestamp(1, controlTime);
lookupTime.setTimestamp(2, controlTime);
lookupTime.setTimestamp(3, controlTime);
Executing the code works fine - no exceptions or warnings are displayed. Nevertheless the resultset returned by
rs = lookupTime.executeQuery();
is empty.
Setting the query to
(2)
SELECT (t1.LOGGED_TIME - TO_TIMESTAMP('2014-08-15 03:52', 'yyyy-mm-dd hh24:mi')) AS TDIFF, t1.ID, t1.STATUS, t1.LOGGED_TIME, t1.SERVER_TIME
FROM table_1 t1
WHERE (
((t1.LOGGED_TIME - TO_TIMESTAMP('2014-08-15 03:52', 'yyyy-mm-dd hh24:mi')) <= INTERVAL '10' DAY)
AND ((t1.LOGGED_TIME - TO_TIMESTAMP('2014-08-15 03:52', 'yyyy-mm-dd hh24:mi')) >= INTERVAL '-10' DAY))
ORDER BY t1.LOGGED_TIME DESC
returns the expected data.
When I query e.g. strings from another column of the same table with a prepared statement the result is ok.
What I'm missing here? Where is the point? Any idea?
To say it clear: the point is not to identify a kind of wrong date/time format conversion in (2). That will always lead to an oracle error message and can be fixed easily.
The question is: why stays the RecordSet returned by the preparedStatement (1) empty (= not a single record) without any error notification? If the Timestamp format is wrong in any way, why there isn't an error or a warning?
Check your TO_TIMESTAMP format:
TO_TIMESTAMP('2014-08-15 03:52',
'dd.mm.yy hh24:mi')
Aug. 14, 2015, not Aug. 15, 2014
Update
Actually, I get the following error when trying that one:
ORA-01843: not a valid month
01843. 00000 - "not a valid month"
Update2
A Java Timestamp maps to an Oracle DATE data type, not a TIMESTAMP. Don't know if that makes a difference, but you might try TO_TIMESTAMP(?).
I would however change the query to allow use of a potential index on LOGGED_TIME:
SELECT ID, STATUS, LOGGED_TIME, SERVER_TIME
FROM table_1
WHERE LOGGED_TIME BETWEEN ? AND ?
ORDER BY LOGGED_TIME DESC
Then do all the math in Java:
Timestamp controlTime = Timestamp.valueOf("2014-08-15 03:52:00");
Calendar cal = Calendar.getInstance();
cal.setTime(controlTime);
cal.add(Calendar.DAY_OF_MONTH, -10);
lookupTime.setTimestamp(1, new Timestamp(cal.getTimeInMillis()));
cal.setTime(controlTime);
cal.add(Calendar.DAY_OF_MONTH, 10);
lookupTime.setTimestamp(2, new Timestamp(cal.getTimeInMillis()));
try (ResultSet rs = lookupTime.executeQuery()) {
while (rs.next()) {
long tdiffInSeconds = (rs.getTimestamp("LOGGED_TIME").getTime() - controlTime.getTime()) / 1000;
// other code
}
}

I'm getting an error in java and mysql connectivity..its related to date comparing in java and mysql

String x=jTextField1.getText();
After connecting to the database the query is:
String query="INSERT INTO student(A) VALUES('"+a+"') where date=' " +x+ " ';";
stmt.executeUpdate(query);
*a is a string which has a letter P assigned to it.
The error i am getting is "....check your mysql syntax....corresponding to the date='"+x'"; "
I want to compare the date entered in the textfield to the date in the mysql 'date' column and if it is correct,the 'a' value (which is P) should be written in column A in the same row of the date entered...
Please help...
Thank you...
I see a space after/before the single quote.
Furthermore date is also an SQL keyword, so better not use that as field name. You could write
`date`
Addition
Sorry, I realized that I erred (date cannot be a field queried as we are inserting a new record).
Either you mean:
String query = "INSERT INTO student(A) VALUES('P') WHERE CURRENT_DATE() = '2012-05-09'";
Or date is a field, and you just want to set another field:
String query = "UPDATE student SET A = 'P' WHERE `date` = '2012-05-09'";
Inserting new records into same table
This is not allowed to do immediately, so one has to use a temporary table.
CREATE TEMPORARY TABLE tmp (A VARCHAR(1));
INSERT INTO tmp (A)
SELECT 'P' FROM student WHERE dt = '...';
INSERT INTO student(A)
SELECT A FROM tmp;
DROP TABLE tmp;

Categories

Resources