JDBC select query with join and like fails - select

I am trying to search the data in two tables by getting the last four numbers of a SSN as input from the user.
I have a JDBC query that is as follows:
`String sql = "SELECT N.NUMBER,N.LAST_NAME,N.FIRST_NAME,M.SSN,M.SEX,M.BIRTH_DATE"
+"FROM" +" G.M_NAME_A N, G.M_ID_A M"
+"WHERE" + "N.NUMBER = M.NUMBER"
+"AND" + "M.SSN like 'l4ssn' ";'
It fails with either "FROM Keyword not found where expected" or "Invalid Column index".
Please help me format the query.

yes, it should fail. Check your SQL, you're missing a space in front of "FROM", and ditto most anywhere you're concatenating strings.

1、Change the SQL as follows. Space is added around FROM, WHERE and AND,If you follow what you write sql, sql stitching is so out:
String sql = "SELECT N.NUMBER,N.LAST_NAME,N.FIRST_NAME,M.SSN,M.SEX,M.BIRTH_DATEFROM G.M_NAME_A N, G.M_ID_A MWHEREN.NUMBER = M.NUMBERAND M.SSN like 'l4ssn' ";
String sql = "SELECT N.NUMBER,N.LAST_NAME,N.FIRST_NAME,M.SSN,M.SEX,M.BIRTH_DATE"
+" FROM G.M_NAME_A N, G.M_ID_A M"
+" WHERE N.NUMBER = M.NUMBER"
-- modify +" AND" + "M.SSN like 'l4ssn' ";'
+" AND M.SSN like '%l4ssn%' ";

Change the SQL as follows. Space is added around FROM, WHERE and AND
String sql = "SELECT N.NUMBER,N.LAST_NAME,N.FIRST_NAME,M.SSN,M.SEX,M.BIRTH_DATE"
+" FROM " +" G.M_NAME_A N, G.M_ID_A M"
+" WHERE " + "N.NUMBER = M.NUMBER"
+" AND " + "M.SSN like 'l4ssn' ";
Your query will look for M.SSN which is 14ssn it's just like saying M.SSN = '14ssn'. If you want to use query something similar to 14ssn use M.SSN like '%14ssn%' instead
Just on side note, use prepared statement instead of using the query parameter in your sql string.
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

Try this query
String sql=" SELECT N.NUMBER,N.LAST_NAME,N.FIRST_NAME,M.SSN,M.SEX,M.BIRTH_DATE "+
" FROM G.M_NAME_A N,G.M_ID_A M "+
" WHERE N.NUMBER = M.NUMBER "+
" AND M.SSN like 'l4ssn' ";

The question is resolved using the following query and PreparedStatement:
String l4ssn=("%"+l4ssn);
String sql = "SELECT N.NUMBER,N.LAST_NAME,N.FIRST_NAME,M.SSN,M.SEX,M.BIRTH_DATE"
+" FROM " +" G.M_NAME_A N, G.M_ID_A M"
+" WHERE " + "N.NUMBER = M.NUMBER"
+" AND " + "M.SSN like ?";
PreparedStatement pstmt = new PreparedStatement(sql);
pstmt.setString(1,l4ssn);

Related

aggregate function as tuple argument postgres

I want to pass aggregate function like min, max etc as query parameter using Tuple.
Below is my query:
"select $5(CAST (vol AS FLOAT)) AS agg_v, "
+ "time_bucket_gapfill" + "(($1::text || ' minutes')::interval, t) AS time_function_minute, "
+ "tag_id from rtdata "
+ "where tag_id = any($2) and t > $3 and t < $4 "
+ "GROUP BY (tag_id, time_function_minute) ORDER BY time_function_minute"
But I'm getting following exception:
io.vertx.pgclient.PgException: syntax error at or near
"("
at io.vertx.pgclient.impl.codec.ErrorResponse.toException(ErrorResponse.java:29)
at io.vertx.pgclient.impl.codec.PrepareStatementCommandCodec.handleErrorResponse(PrepareStatementCommandCodec.java:62)
at io.vertx.pgclient.impl.codec.PgDecoder.decodeError(PgDecoder.java:233)
at io.vertx.pgclient.impl.codec.PgDecoder.decodeMessage(PgDecoder.java:122)
at io.vertx.pgclient.impl.codec.PgDecoder.channelRead(PgDecoder.java:102)
at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:253)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:352)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1422)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:374)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:360)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:931)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:700)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:635)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:552)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:514)
at io.netty.util.concurrent.SingleThreadEventExecutor$6.run(SingleThreadEventExecutor.java:1044)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:745)
But If I replace $5 with hardcode aggregate function it works. How can I pass aggregate function dynamically in this scenario?
RxJava code Snippet:
return txBegin()
.flatMapObservable(tx ->
tx.rxPrepare(abovesql)
.flatMapObservable(pq -> {
return pq.createStream(50,
Tuple.of(
evalBucketInterval(req),
req.getTags().toArray(new Integer[0]),
parse(req.getStartDate()),
parse(req.getEndDate()),
parse(req.getAggFunc())))
.toObservable();
})
.doAfterTerminate(tx::commit))
.map(this::toFuncJson);
PostgreSQL allows to use parameters only as values and doesn't understand when you try to use parameters for function names, table names, etc. So you cannot pass aggregate name as a parameter.
I suggest to work around it in your application by concatenating the string value containing the aggregate function name. I guess it can be something like, but I am not sure about the exact syntax and what limitations of your environment are:
"select "+ my_agg_func_name +"(CAST (vol AS FLOAT)) AS agg_v, "
+ "time_bucket_gapfill" + "(($1::text || ' minutes')::interval, t) AS time_function_minute, "
+ "tag_id from rtdata "
+ "where tag_id = any($2) and t > $3 and t < $4 "
+ "GROUP BY (tag_id, time_function_minute) ORDER BY time_function_minute"

unexpected token: :(colon) in Hibernate

I'm trying to do the following code, but i get the unexpected token: : near line 1 error which refer to ord.date_out::date. Here is my code
#Query(value="select new com.ameerarestapi.wrapper.report.SummaryPeriodicSales(sto.name, sum(odi.subtotal_price), sum(odi.qty), ((sum(odi.subtotal_price))/(sum(odi.qty))), ord.date_out::date) "
+ "from OrderDetailItem odi "
+ "left join odi.order as ord "
+ "left join ord.store as sto "
+ "where ord.store.principle = :principle and ord.orderStatus IN :orderstatus and ord.dateOut between :date1 and :date2 and ord.voidStatus = :voidStatus "
+ "group by sto.name, ord.date_out::date ")
List<SummaryPeriodicSales> getReportDaily(#Param("principle") Principle principle,#Param("orderstatus") List<OrderStatus> orderstatus,#Param("date1") Date date1,#Param("date2") Date date2,#Param("voidStatus") byte voidStatus);
I'm using postgre database
Use the standard CAST() operator instead:
CAST(ord.date_out AS date)

ADO.NET working with SQL and database

I'm getting an exception error saying missing operators can anyone help
string sql = "Select SalesPerson.Name, Item.Description, Orders.Quantity, Orders.OrderDate"
+ "From([Orders]"
+ "Inner Join[SalesPerson] On Orders.SalesPersonID=SalesPerson.SalesPersonID)"
+ "Inner Join[Item] On Orders.ItemNumber=Item.ItemNumber"
+ "Where Orders.CustomerID=#customer Order by Orders.OrderDate DESC";
You need to add some spaces at the end of each of your lines of SQL!
string sql = "SELECT SalesPerson.Name, Item.Description, Orders.Quantity, Orders.OrderDate "
+ "FROM [Orders] "
+ "INNER JOIN [SalesPerson] ON Orders.SalesPersonID = SalesPerson.SalesPersonID "
+ "INNER JOIN [Item] ON Orders.ItemNumber = Item.ItemNumber "
+ "WHERE Orders.CustomerID = #customer "
+ "ORDER BY Orders.OrderDate DESC";
Otherwise, your SQL ends up being
Select ..... Orders.OrderDateFROM([Orders]Inner Join[SalesPerson] .....
and so on - and that's just not valid SQL.
I also removed some unnecessary parenthesis around the JOIN operators - those are only needed for MS Access, but since you're saying you're using ADO.NET, I assume this is not for MS Access and therefore, those parenthesis are not needed

Syntax error in Postgresql but not mySQL

I'm executing this query
String innerQueryWithProductVersion = "select test_suite_name, max(m.date) as date "
+"from master_table_test_runs m "
+"INNER JOIN processed_jenkins_runs pdup "
+"ON m.id=pdup.test_run_id where m.date < "
+"(select max(date) from master_table_test_runs "
+"where product_version =:productVersion) "
+"and m.test_type!='CLOVER' and m.product = :product "
+"and m.test_suite_name in "+missingSuites
+" and m.branch like "+filters.branch
+" and m.deployment_mode like "+filters.deploymentMode
+" and pdup.jenkins_server like "+filters.jenkinsInstance
+" group by m.test_suite_name";
String queryWithProductVersion = "select t.number_tests, "
+"t.number_failure, t.number_skip, t.number_errors, t.test_type, "
+"t.product_version, t.date, t.test_suite_name, "
+"t.branch, p.job_url "
+"from master_table_test_runs t INNER JOIN "
+"(" +innerQueryWithProductVersion+") as x "
+"INNER JOIN processed_jenkins_runs p ON t.id=p.test_run_id "
+"where t.test_suite_name = x.test_suite_name "
+"and t.date = x.date and t.test_suite_name "
+"in "+missingSuites+" and product = :product "
+"and p.jenkins_server like "+filters.jenkinsInstance
+" and t.branch like "+filters.branch
+" and t.deployment_mode like "+filters.deploymentMode+"";
This query its working fine in mysql, but in PostgreSQL its giving syntax errors at "where" and "and"
syntax error at or near 'and'
Can anyone help me figure out the problem?
one of "+missingSuites, "+filters.branch etc is not defined, look at sample:
t=# select true where 'a' like '' and true;
bool
------
(0 rows)
t=# select true where 'a' like /*missed value*/ and true;
ERROR: syntax error at or near "and"
LINE 1: select true where 'a' like /*missed value*/ and true;

parsing error in jpa query getting parsing error

StringBuffer query = new StringBuffer();
query.append("SELECT e FROM DBMGPersonMetaData e WHERE
e.moduleUniqueId.extension= ?1 AND e.ConsType ");
query.append("IN ( SELECT CASE WHEN " +"INSTR(p.description, ' ') = 0 "+
" THEN SUBSTR(p.description,1) "+ " WHEN INSTR(p.description, ' ') !=0 "+
" THEN SUBSTR(p.description,1,INSTR(p.description, ' ')-1) END"+ " AS ee FROM DBProjectMetaData p WHERE p.projectUniqueId.extension= ?2");
dbModuleperson = (DBMGPersonMetaData)
entityManager.createQuery(query.toString()).setParameter(1,"12").
setParameter(2,"12").getSingleResult();
In order to run the native SQL query in JPA, you should use this method instead:
entityManager.createNativeQuery(query.toString());
The method you're using (createQuery) accepts either JPQL query or the CriteriaQuery.