Comparing EXTRACT(YEAR FROM table.date) to variable value in IntelliJ IDE - java

I'm trying to get flight count(rate) per month for particular variable year from my database using following query:
SELECT EXTRACT(MONTH FROM departure_date) AS month, COUNT(*) AS flight_rate
FROM flight
WHERE EXTRACT(YEAR FROM departure_date) = ?
GROUP BY EXTRACT(MONTH FROM departure_date);
Then, I have following Java code:
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, Integer.parseInt(yearTxtField.getText()));
The number 1 in prepStatement.setInt(...) keeps being underlined with an error saying:
Cannot resolve query parameter 1
So, my query is obviously wrong.
My question is, how to compare the extracted year in where clause with variable year input from text field, using prepared statement?
EDIT: So, after I've tried to run the code anyway, ignoring IDE underline error, everything works fine and I will get the wanted result. However when I'm trying to run this query alone in intelliJ with right click and execute, I will get an error:
[2016-04-09 02:34:09] [42601] ERROR: syntax error at or near "GROUP"
Position: 135

Not sure if related to that error message, but PostgreSQL's extract function returns a double precision (more here).
So you might want to try setDouble(int parameterIndex, double x) instead of setInt(int parameterIndex, int x).

Related

JDBC SqlSyntaxErrorException but statement works in SQL tool

I have a DB2 MERGE INTO statement that gives me a sql syntax exception when I try to execute it from Java, but when I put in the parameters in my SQL tool it runs just fine. I've run this repeatedly both in my SQL tool and in Java, and it always works in the former but fails in the latter. This is the SQL (table and column names have been changed to protect the innocent):
merge INTO sales_table AS target
USING (VALUES ( CAST('2020' AS CHAR(4)), CAST('12' AS CHAR(2)), CAST('AB01' AS CHAR(4)), CAST
(0555.0 AS
DECIMAL(9)), CAST(0.000 AS DECIMAL(9)), CAST('DP079616' AS CHAR(8)) )) AS input_data (
year, month, location, no, orig_no, last_upd_userid )
ON ( target.year = input_data.year
AND target.month = input_data.month
AND target.location = input_data.location )
WHEN matched THEN
UPDATE SET no = input_data.no,
orig_no = input_data.orig_no,
last_upd_userid = input_data.last_upd_userid,
last_upd_tmstmp = CURRENT TIMESTAMP
WHEN NOT matched THEN
INSERT ( year,
month,
location,
no,
orig_no,
creation_userid,
creation_tmstmp,
last_upd_userid,
last_upd_tmstmp )
VALUES ( input_data.year,
input_data.month,
input_data.location,
input_data.no,
input_data.orig_no,
input_data.last_upd_userid,
CURRENT TIMESTAMP,
input_data.last_upd_userid,
CURRENT TIMESTAMP )
In the query above I have replaces the ?s with hard-coded parameters that Java sets with the set... methods.
I get this exception in Java:
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-270, SQLSTATE=42997, SQLERRMC=null, DRIVER=4.21.29
This is the relevant Java part:
req.setString(i++, roaa.getYear());
req.setString(i++, roaa.getMonth());
req.setString(i++, roaa.getLocatoin());
req.setFloat(i++, Float.parseFloat(roaa.getSalesNumber()));
req.setFloat(i++, Float.parseFloat(roaa.getOrigSalesNumber()));
req.setString(i++, userId);
req.executeUpdate();
Any thoughts on why I'd get a syntax exception on something that works in my SQL tool? Obviously the syntax is right if it works. I've Googled the SQL code -270, and various results say it's because it violates a constraint somewhere, but again, it works in the SQL tool, so I can't help thinking I'm overlooking something simple that should be obvious to me.

Oracle Package or function ... is in an invalid state

I stuck with Oracle store procedure calling. The code looks simple, but I seriously don't know how to make it work.
This is my code for creating the procedure
DELIMITER ##
CREATE OR REPLACE PROCEDURE updateAward(_total_amount in Number, _no_of_sales in Number, _agent in NUMBER, _id in NUMBER) AS
BEGIN
update Award set total_amount = _total_amount, no_of_sales = _no_of_sales, agent_id = _agent where ID = _id ##
commit ##
So, when I execute it through NetBean (it is the only tool I have at this moment), the code run well.
I also tried to run the compile statement
alter PROCEDURE updateAward compile;
and then, use
select *
from user_errors
where name = 'ORG_SPGETTYPE'
The select return empty, proving that the compile process is ok. However, when I trigger the procedure
call updateAward(1,1,1,1);
It returns the error
Package or function UPDATEAWARD is in an invalid state
and the command
SELECT object_name FROM user_objects WHERE status='INVALID';
return the name of the procedure. How can I solve this problem ?
Update 1:
if I use
BEGIN
updateAward(1,1,1,1);
End;
I got error
Error code 6550, SQL state 65000: ORA-06550: line 2, column 20:
PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
:= . ( % ;
Update 2:
The reason I put the deliminator is because i got error with ";" when working through some vpn to the other network (still not sure why). So, i updated the code like your answer, but then, with the End; in the end of the procedure and then, get the Invalid SQL statement1. If i remove it and execute (through Netbean), the procedure is created successfully. However, after compiling and check the user_errors, it got the
"PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following: ; "
First things first, your procedure syntax looks wrong. Don't use DELIMITER as that syntax is specific to MySQL. Instead, try something like the following.
CREATE OR REPLACE PROCEDURE updateAward(_total_amount in Number, _no_of_sales in Number, _agent in NUMBER, _id in NUMBER) AS
BEGIN
update Award set total_amount = _total_amount, no_of_sales = _no_of_sales, agent_id = _agent where ID = _id;
commit;
END;
Firstly, there are a couple of things wrong with your procedure:
You're not using delimiters correctly. Delimiters should be used to terminate the whole procedure, not each line.
The NetBeans SQL window doesn't know SQL very well so it cannot tell when the procedure ends and something else begins. Normally, it uses semicolons (;) to tell when one statement ends and another begins, but stored procedures can contain semicolons within them so that wouldn't work. Instead, we change the delimiter to something else so that the NetBeans SQL window sends the entire stored procedure to the database in one go.
Variable names are not allowed to begin with an underscore (_). In particular, rule 5 in the list of Schema Object Naming Rules at this Oracle documentation page states that
Nonquoted identifiers must begin with an alphabetic character from your database character set.
Underscores are not alphabetic characters.
I've taken your procedure, fixed the use of delimiters and added an extra p onto the front of each parameter name (p for 'parameter'), and I got the following, which ran successfully in NetBeans and created a procedure without errors:
delimiter $$
CREATE OR REPLACE PROCEDURE updateAward(p_total_amount in Number, p_no_of_sales in Number, p_agent in NUMBER, p_id in NUMBER) AS
BEGIN
update Award set total_amount = p_total_amount, no_of_sales = p_no_of_sales, agent_id = p_agent where ID = p_id;
commit;
END;
$$
delimiter ;
Secondly, you write
[...] and then, use
select *
from user_errors
where name = 'ORG_SPGETTYPE'
The select return empty, proving that the compile process is ok.
Um, no. This proves that there are no errors in the procedure ORG_SPGETTYPE (or no procedure with that name exists). Your procedure is named updateAward, which Oracle will capitalise to UPDATEAWARD. Try
select *
from user_errors
where name = 'UPDATEAWARD';
instead.

An inconsistency with SQL in ORACLE

When I do the following query I get this error message:
ORA-29913: error in executing ODCIEXTTABLEFETCH callout
ORA-01722: invalid number
The query is
select l.LanguageName as language
from mpi_provider.mpiprovider m, mpi_provider.provlanguage l
where m.providerid = l.providerattestid and m.npi = 1548204944
I thought maybe it was just too high of a number, but when I use both/either
m.npi = 1548204943 or m.npi = 1548204945 the query works fine (though there are no records found). If I add another digit, m.npi = 15482049449, it works fine as well as if I cut off a digit.
I can't figure out what is going on. Any ideas?
npi is defined as Number(10) and can be null

Resultset not returning output

I am trying to run this code but there is no output. But when I run the SQL query from my terminal, it works. Please help.
Statement stmt = conn.createStatement();
ResultSet rset1=stmt.executeQuery("SELECT ShowTime FROM Movie M, screens s WHERE M.MovieID = s.MovieID AND M.MovieID= 01");
while(rset1.next()){
//String tite=(rset1.getTimestamp("title"));
System.out.println(rset1.getString("Showtime"));
//text_39.append((rset1.getString("Showtime"))+"\n");
}
The problem is ResultSet.getString(String) is not case insensitive. Changing the value to System.out.println(rset1.getString("ShowTime")); should solve your problem
if M.MovieID is an numeric data type, the 01 will get truncated to just 1 which will not compare correctly with a string data type of '01' you may need to wrap your '01' in tics so it looks like WHERE M.MovieID = s.MovieID AND M.MovieID= '01'
My thought here is that the Driver and DB engine are doing some implicit casting which is preventing a syntax error but causing you to get no results when run though the driver.
To better answer the question I would need to know what data type MovieID is in Movie table and screens table.

Getting MySQLSyntaxErrorException?

I have this code :
String check="SELECT COUNT(*) as check FROM recordstudent WHERE STUDENT_ID="+T_STUDENT_ID+" AND COURSE_ID="+T_COURSE_ID+" AND PACKAGE_ID="+T_PACKAGE_ID+" AND ACTIVITY_ID="+T_ACTIVITY_ID+" AND DATE="+T_DATE+ ";";
rs=myStmt.executeQuery(check);
int ch=0;
while(rs.next()){
ch=Integer.parseInt(rs.getString("check"));
}
if(ch==0)
{
String insertRecord="insert into recordstudent"+
"(STUDENT_ID,COURSE_ID,PACKAGE_ID,ACTIVITY_ID,TEST_NAME,DATE,SCORE,TOTAL_MARKS,PERCENTAGE,CORRECT_ANSWER,TOTAL_QUESTIONS,STUDENT_NAME,SCORE_PER_DIVISION,ATTEMPTS)"+
"VALUES("+
"'"+T_STUDENT_ID+"',"+
"'"+T_COURSE_ID+"',"+
"'"+T_PACKAGE_ID+"',"+
"'"+T_ACTIVITY_ID+"',"+
"'"+T_TEST_NAME+"',"+
"'"+T_DATE+"',"+
"'"+T_SCORE+"',"+
"'"+T_TOTAL_MARKS+"',"+
"'"+T_PERCENTAGE+"',"+
"'"+T_CORRECT_ANSWERS+"',"+
"'"+T_TOTAL_QUESTIONS+"',"+
"'"+T_STUDENT_NAME+"',"+
"'"+T_SCORE_PER_DIVISION+"',"+
"'"+t+"'"
+");";
myStmt.execute(insertRecord);
}
This snippet should insert the data in database only if the ch=0 .But I am getting this error:
com.mysql.jdbc.exceptions.jdbc4.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
'check FROM recordstudent WHERE STUDENT_ID=11 AND COURSE_ID=2 AND PACKAGE_ID=11 A'
at line 1
Can Anyone help me and solve my problem ?
Fundamentally: don't build your SQL this way. I notice that you've put quotes round the values in the "insert" SQL statement - but not in the "select" one. That's the start of the problem - but you shouldn't be including values like this in your SQL to start with. You should use parameterized SQL via PreparedStatement, and set values for the parameters. Benefits:
You can see your actual SQL more easily, so you'll be able to spot syntax errors. (This is basically keeping your code separate from your data.)
(Very important) You won't be open to SQL injection attacks
You won't need to worry about conversion issues for numbers, dates and times etc
There are other problems in your SQL (such as spaces and check being a reserved word in MySQL), but the very first thing you should fix is how you use values. Until you've done that, your code is inviting security problems.
(You should then start using more conventional variable names than T_STUDENT_NAME etc, but that's a different matter.)
check is a reserved word. Surround it with backticks: `check`
Try this
SELECT COUNT(*) as 'check' FROM recordstudent....
instead of
SELECT COUNT(*) as check FROM recordstudent....
I think check is a keyword

Categories