SQL Error saying that I have not specified a 3rd Parameter - java

I am developing a Java Restful Web Application. When I try to execute this SQL Query using JDBCTemplate it gives and error saying that,
SEVERE: Servlet.service() for servlet [spring-mvc] in context with path [/paf_project] threw exception [Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [select count(*) from customer where email = ? AND password = ? AND status = ?]; nested exception is java.sql.SQLException: No value specified for parameter 3] with root cause
java.sql.SQLException: No value specified for parameter 3
Here is my Function which I am going to get the row count of my table.
public int userLogin(String un, String pw) {
String status = "active";
String sql = "select count(*) from customer where email = ? AND password = ? AND status = ?";
int count = template.queryForObject(sql, new Object[] {un, pw, status}, Integer.class);
if(count >= 1) {
return 1;
}

Related

JPA repository Boolean Query - return null pointer exception

I have Java springBoot project
With repository that included boolean custom query.
but the system run to null pointer exception apart from return "false".
this is the query:
#Query(value = "select * from customers_vs_coupons where customer_id =? and coupon_id = ?", nativeQuery = true)
Boolean existsPurchesedCoupon(int customerId, int couponId);
I called the method:
if (customerRepository.customerPurchesedCoupon(customerId, coupon.getId())) {
throw new PurchaseCouponException("can buy only once.");
and this is the error:
[Request processing failed; nested exception is java.lang.NullPointerException: Cannot invoke "java.lang.Boolean.booleanValue()" because the return value of "com.chana.repositories.CustomerRepository.customerPurchesedCoupon(int, int)" is null] with root cause ```
Your query
select * from customers_vs_coupons where customer_id =? and coupon_id = ?
is designed to return whatever entity (called CustomersVsCoupons from now on) is mapped to the table customer_vs_coupons, not a Boolean.
If you want to throw an exception whenever a specific customer already has a coupon affected, you should transform the signature of your method to either:
Return a CustomersVsCoupons, and throw an exception if your query did not return null
Return an Optional<CustomersVsCoupons>, and throw an exception if your query did return a non empty Optional

How to write SQL query in Java to get data from Snowflake

I am trying to write this Snowflake query into Java code:
copy into s3://snowflake171
from USER_TABLE
storage_integration = s3_int
file_format = CSV_TEST;
I am writing it like this:
String q ="COPY INTO s3://snowflake171\n" +
" FROM \"TEST\".\"PUBLIC\".\"USER_TABLE\"WHERE\"ID\\\"=?\"\n" +
" storage_integration = s3_int\n" +
" file_format = CSV_TEST";
But I am getting this error:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [COPY INTO s3://snowflake171
FROM "TEST"."PUBLIC"."USER_TABLE"WHERE"ID\"=?"
storage_integration = s3_int
file_format = CSV_TEST]; nested exception is net.snowflake.client.jdbc.SnowflakeSQLException: SQL compilation error:
syntax error line 1 at position 5 unexpected '<EOF>'.
What am I missing?
As the latest error message is "SQL access control error: Insufficient privileges to operate on integration 'S3_INT'", can you try to grant USAGE permission on s3_int to your role? Are you sure you set the correct role when connecting?
String url = "jdbc:snowflake://<account_identifier>.snowflakecomputing.com";
Properties prop = new Properties();
prop.put("user", "<user>");
prop.put("privateKey", PrivateKeyReader.get(PRIVATE_KEY_FILE));
prop.put("db", "<database_name>");
prop.put("schema", "<schema_name>");
prop.put("warehouse", "<warehouse_name>");
prop.put("role", "<role_name>");

PostgreSQL Full Text Search with Hibernate Query Language cannot execute query

I am developing a full text search service. I use PostgreSQL's built-in FTS query syntax. As you know, I need to use ## characters to use it. But, this characters are not recognized by HQL, you cannot directly write it like inside the sql. One option is to use nativeQuery, which I used to use. But, due to software's requirements, now I need to use HQL. For this purpose, I tried to implement this implementation.
In that implementation first you create a PostgreSQLFTSFunction class. For me it is:
public class BFTSFunction implements SQLFunction {
#Override
public boolean hasArguments() {
return true;
}
#Override
public boolean hasParenthesesIfNoArguments() {
return false;
}
#Override
public Type getReturnType(Type type, Mapping mapping) throws QueryException {
return new BooleanType();
}
#Override
public String render(Type type, List list, SessionFactoryImplementor sessionFactoryImplementor)
throws QueryException {
if (list.size() != 2) {
throw new IllegalArgumentException("The function must be passed 3 args");
}
String field = (String) list.get(0);
String value = (String) list.get(1);
String fragment = null;
fragment = "( to_tsvector(coalesce(" + field + ",' ')) ## " + "plainto_tsquery('%" +
value + "%')) ";
return fragment;
}
}
Then need to create CustomPostgreSQLDialect:(I have, for sure, added dialect configuration onto application.yml file)
public class FTSPostgresDialect extends PostgisDialect {
public FTSPostgresDialect() {
super();
registerFunction("fts", new BFTSFunction());
}
}
Lastly I created HQL in my RepositoryImp
Query<Long> q = session.createQuery(
"select b.id from B b where (fts(b.name,:searched) = true )",Long.class).setParameter("searched",searched);
List<Long> listResults = q.getResultList();
But the query created by hibernate cannot be executed. Full error will be given below, but I should say that, logged query in the console (created by Hibernate) can be executed in pgAdmin. Therefore, Query creation process is correct. Then, where can be the error is?
Full error is given:
rg.springframework.dao.DataIntegrityViolationException: could not execute query; SQL [select b0_.id as col_0_0_ from bs b0_ where ( b0_.deleted=false) and ( to_tsvector(coalesce(b0_.name,' ')) ## plainto_tsquery('%?%')) =true]; nested exception is org.hibernate.exception.DataException: could not execute query
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261) ~[spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:223) ~[spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE]
...
Caused by: org.hibernate.exception.DataException: could not execute query
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:118) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
...
Caused by: org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:65) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.core.v3.SimpleParameterList.setStringParameter(SimpleParameterList.java:128) ~[postgresql-42.2.5.jar:42.2.5]
2019-07-16 10:08:59.328 ERROR 8248 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute query; SQL [select b0_.id as col_0_0_ from bs b0_ where ( b0_.deleted=false) and ( to_tsvector(coalesce(b0_.name,' ')) ## plainto_tsquery('%?%')) =true]; nested exception is org.hibernate.exception.DataException: could not execute query] with root cause
org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:65) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.core.v3.SimpleParameterList.setStringParameter(SimpleParameterList.java:128) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.jdbc.PgPreparedStatement.bindString(PgPreparedStatement.java:996) ~[postgresql-42.2.5.jar:42.2.5]
If additional info is needed, I will fastly send it. Thanks in advance.
Interestingly, as the error suggests, hibernate cannot bind the parameters onto sql. I couldn't make it happen. But in my situation, I could just concatenate as string, therefore problem is resolved by changing HQL from:
Query<Long> q = session.createQuery(
"select b.id from B b where (fts(b.name,:searched) = true )",Long.class)
.setParameter("searched",searched);
to:
Query<Long> q = session.createQuery(
"select b.id from B b where (fts(b.name,"+searched+") = true )",Long.class);
The problem is unnecessary quotes in a plainto_tsquery call:
fragment = "( to_tsvector(coalesce(" + field + ",' ')) ## " + "plainto_tsquery('%" +
value + "%')) ";
It should be:
fragment = "( to_tsvector(coalesce(" + field + ",' ')) ## " + "plainto_tsquery(" +
value + ")) ";
I removed those % too, because it won't work like that. value won't have an actual parameter value, it would have ? in it to create a query, that will be reused for actual executions. If you want to wrap the given value into %, you'll have to do it with SQL, not Java code.

how we can fix "java.sql.SQLSyntaxErrorException: [duplicate]

This question already has answers here:
SQL query: Can't order by column called "order"?
(7 answers)
Closed 3 years ago.
i want to show the list of orders through api but we have an error in the DAO SQLSyntaxErrorException.
#RequestMapping("list")
public String getAllOrders() {
//APIResponse response=new APIResponse();
List<OrderBeans> orderList = orderDao.selectAll();
return new Gson().toJson(orderList);
}
public List<OrderBeans> selectAll() {
System.out.println("DAO => " + jdbcTemplate);
List<OrderBeans> orders = null;
String query = "select * from " + TABLE_ORDER +"";
try {
orders = jdbcTemplate.query(query, new OrderRowMapper());
} catch (EmptyResultDataAccessException | IncorrectResultSetColumnCountException e) {
}
return orders;
}
3-May-2019 15:01:15.997 SEVERE [http-nio-8084-exec-109] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [/Grocery] threw exception [Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [select * from order]; nested exception is java.sql.SQLSyntaxErrorException: 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 'order' at line 1] with root cause
java.sql.SQLSyntaxErrorException: 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 'order' at line 1
I am speculating here that your error is due to your SQL table being called ORDER, which of course is a reserved keyword in almost all versions of SQL. You should always avoid naming your tables and columns with reserved keywords. As a workaround, you could build your query as follows, placing backticks around the table name:
String query = "select * from `" + TABLE_ORDER + "`";
However, the above should only be viewed as a temporary solution until you get a chance to fix your data model.

Calling query having multiple IN Clause from JAVA

This query runs fine from SQL Developer : select * from MYTABLE where (field1, field2) IN (('A', '1'), ('B','2'), ('C','3')) ;
But when I try to call it from java I am getting exception.
public List<MYVO> callDB(List<String> sourceAndIdList) {
System.out.println(sourceAndIdList);
String query = "select * from MYTABLE where (field1, field2) IN (:source_monitorId_list)";
Map<String, List<String>> namedParameters = Collections.singletonMap("source_monitorId_list", sourceAndIdList);
return this.namedParameterJdbcTemplate.query(query , namedParameters, new RowMapper<MYVO>() {
#Override
public MYVO mapRow(ResultSet rs, int rowNum) throws SQLException {
....
}
});
}
One printing my list I am getting : [('A', '1'), ('B', '2'), ('C', '3')]
Exception:
SEVERE: Servlet.service() for servlet [selfservice] in context with
path [/mymonitoring] threw exception [Request processing failed;
nested exception is org.springframework.jdbc.BadSqlGrammarException:
PreparedStatementCallback; bad SQL grammar [select * from MYTABLE
where (field1, field2) IN (?, ?, ?)]; nested exception is
java.sql.SQLSyntaxErrorException: ORA-00920: invalid relational
operator ] with root cause java.sql.SQLSyntaxErrorException:
ORA-00920: invalid relational operator
EDIT: This is not a duplicate as I am looking for a solution with springs NamedParameterJdbcTemplate for a query having multiple IN clause and the size of parameters are known only at runtime.
You can't use bind parameter like this in an "IN".
Either you do :
IN ((:p1, :p2), (:p3,:p4), (:p5,:p6))
But it assumes you know exactly how many items you have (in this case 3) or you "materialize" your parameters in the SQL string:
String query = "select * from MYTABLE where (field1, field2) IN (('A', '1'), ('B', '2'), ('C', '3'))";

Categories

Resources