NamedParameterJdbcTemplate with SQL Server : Incorrect syntax near '#P0' - sql

I have the following code which runs a query against a SQL Server DB. I've read these links
http://jenikya.com/blog/2009/02/sqlexception-select-top-number.html
MS SQL Exception: Incorrect syntax near '#P0'
but i still can't see where/why i'm getting the '#P0' issue. I've wrapped the TOP parameter in brackets.
private String DEP_AMC_QUERY = "SELECT TOP(1) ((fund_amc-reinsurance_premium)/1000)
as dep_amc "+
"FROM Hedging_Staging.dbo.:table "+
"WHERE internal_fund_code_identifier=:fund "+
"AND load_id=:load_id;";
public BigDecimal getDepAmcValue(String fund,Long load_id,String table){
NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(getDataSource());
//Set up parameters
MapSqlParameterSource namedParameters = new MapSqlParameterSource("fund",fund);
namedParameters.addValue("load_id",load_id);
namedParameters.addValue("table",table);
MapUtils.debugPrint(System.out,"params", namedParameters.getValues());
//Execute query
return jdbcTemplate.queryForObject(DEP_AMC_QUERY,namedParameters,BigDecimal.class);
}
The console and exception message is
13:11:12,871 INFO [ReinsuredFundAssetProcessor] looking up dep_amc value for AXX in AI_IFL_Policy table.
params =
{
table = AI_IFL_Policy java.lang.String
fund = AXX java.lang.String
load_id = 4356 java.lang.Long
}
13:11:12,909 ERROR [AbstractStep] Encountered an error executing the step
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [select top(1) ((fund_amc-reinsurance_premium)/1000) as dep_amc from Hedging_Staging.dbo.? WHERE internal_fund_code_identifier=? AND load_id=?;]; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '#P0'.
at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:98)
Any ideas?

Related

How to correct bad sql grammar when passing data?

This is my JDBC file with a the following sql query:
private static final String UPDATE_QUESTION = "UPDATE Quiz SET type=?, questionIndex=?, choiceNum=?, question=?, choiceA=?, choiceB=?, choiceC=?, choiceD=?, correct=?, hint=? WHERE type=? AND questionIndex=?";
When I try and pass some data into the query above in JSON format:
{
"id": 84,
"type":"epidemics",
"questionIndex": 1,
"choiceNum":2,
"question":"updated question3",
"choiceA": "no3",
"choiceB":"yes2",
"choiceC":"no3",
"choiceD":"yes4",
"correct":"no3",
"hint":"second answer"
}
I am getting the following error message:
"timestamp": "2022-11-26T11:52:16.431+00:00",
"status": 500,
"error": "Internal Server Error",
"trace": "org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [UPDATE Quiz SET type=?, questionIndex=?, choiceNum=?, question=?, choiceA=?, choiceB=?, choiceC=?, choiceD=?, correct=?, hint=? WHERE (type=?) AND (questionIndex=?)]; nested exception is java.sql.SQLException: No value specified for parameter 12
Any ideas where I'm going wrong in the query?
Note that you need to pass a value for each ? placeholder, even if the same column appears more than once in the prepared statement. So, you need to bind the value for questionIndex twice. Your Java code should look something like:
String UPDATE_QUESTION = "UPDATE Quiz SET type=?, questionIndex=?, choiceNum=?, question=?, choiceA=?, choiceB=?, choiceC=?, choiceD=?, correct=?, hint=? WHERE type=? AND questionIndex=?";
PreparedStatement ps = conn.prepareStatement(UPDATE_QUESTION);
ps.setString(1, type);
ps.setInt(2, questionIndex); // first setter for questionIndex
ps.setInt(3, choiceNum);
ps.setString(4, question);
ps.setString(5, choiceA);
ps.setString(6, choiceB);
ps.setString(7, choiceC);
ps.setString(8, choiceD);
ps.setString(9, correct);
ps.setString(10, hint);
ps.setString(11, type);
ps.setInt(12, questionIndex); // second setter for questionIndex
int row = ps.executeUpdate();
// rows affected
System.out.println(row);

Spring JPA: could not extract ResultSet, ERROR: syntax error at or near "{"

I am trying to retrieve a list of paginated data, with #query
#Query(value = "SELECT * FROM message WHERE id IN( SELECT max(id) FROM message WHERE receiver = ?1 OR sender = ?2 group by receiver,sender) AND (receiver = ?1 OR sender= ?2) #{#pageable}",
nativeQuery = true)
Page<Message> findDistinctMessages(User sender, User receiver, Pageable pageable);
but i keep getting an error when I call the method:
11:57:43 [thread] WARN o.h.e.jdbc.spi.SqlExceptionHelper -SQL Error: 0, SQLState: 42601
2018-06-18 11:57:43 [thread] ERROR o.h.e.jdbc.spi.SqlExceptionHelper -ERROR: syntax error at or near "{"
Position: 162
2018-06-18 11:57:43 [thread] ERROR 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.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: ERROR: syntax error at or near "{"
Position: 162
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2455)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2155)
This is my Message class
#Entity
#Table(name = "Message")
public class Message extends DefaultEntity {
#Valid
#ManyToOne(targetEntity = User.class)
#JoinColumn(name="sender")
private User sender;
#Valid
#ManyToOne(targetEntity = User.class)
#JoinColumn(name="receiver")
private User receiver;
#NotNull
private String message;
#Enumerated(EnumType.STRING)
private MessageStatus messageStatus;
private Boolean isRead;
}
I have searched for answers, but to no avail, Please what could be the issue.
Just remove the #{#pageable} from the query. This kind of stuff was a workaround for a bug in Spring Data JPA which is fixed in the current versions.
See https://jira.spring.io/browse/DATAJPA-928
#Query(value = "SELECT * FROM message WHERE id IN( SELECT max(id) FROM message WHERE receiver = ?1 OR sender = ?2 group by receiver,sender) AND (receiver = ?1 OR sender= ?2) #{#pageable}",
nativeQuery = true)
to
#Query(value = "SELECT * FROM message WHERE id IN( SELECT max(id) FROM message WHERE receiver = ?1 OR sender = ?2 group by receiver,sender) AND (receiver = ?1 OR sender= ?2) \n-- #pageable\n",
nativeQuery = true)
postrges took {#pageable}" as a code instead of a comment, changing it to \n-- #pageable\n", will make postrges see it as a real comment.

Ignite Query Exception

Im getting the following error:
Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "SELECT
""standard_item_cache"".""STANDARDITEM""._KEY,
""standard_item_cache"".""STANDARDITEM""._VAL FROM
""standard_item_cache"".""STANDARDITEM"" WHERE ITEMID[*] == ? "; SQL statement:
SELECT "standard_item_cache"."STANDARDITEM"._KEY,
"standard_item_cache"."STANDARDITEM"._VAL FROM
"standard_item_cache"."STANDARDITEM" WHERE itemId == ? [42000-196]
When I try to perform a simple query:
String itemId = params.get(Params.PARAM_ITEM_ID);
SqlQuery<String, StandardItem> sql = new SqlQuery<>(StandardItem.class, "itemid == ?");
try (QueryCursor<Cache.Entry<String, StandardItem>> cursor = standardItemIgniteCache.query(sql.setArgs(itemId))) {
logger.info("publish standard items from cache");
for (Cache.Entry<String, StandardItem> entry : cursor) {
logger.info("publish standard item: " + entry.getValue().toString());
}
logger.info("publishing standard items from cache done");
cursor.close();
}
Where is the mistake? Im doint it exactly like it is described in the apache ignite examples: https://apacheignite.readme.io/v1.0/docs/cache-queries
The mistake is in this tiny string: itemid == ?.
You used == instead of =. SQL equality operator is a single =.

How do I switch database using a PreparedStatement (worried about sql injection)?

I have a simple jdbc application that talks to a sql server.
Can I use the "use databaseName" in a PreparedStatement.
void useDatabase(Statement statement, String databaseName) throws SQLException {
//This works but I was worried about sql injection as
//databaseName is provided by the user.
//statement.executeUpdate("use \"" + databaseName + "\"");
//So I tried this but I am
//Getting com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '#P0'.
PreparedStatement preparedStatement = statement.getConnection().prepareStatement("use ?");
preparedStatement.setString(1, databaseName);
preparedStatement.executeUpdate();
}
Use keyword docs:
https://technet.microsoft.com/en-us/library/ms188366.aspx

SQL update not running, reasons unknown

I am trying to run an update and for reasons I cannot figure out why it is not running.
The error:
Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 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 'WHERE EventID = '2'' at line 4
I cannot figure out what is wrong with the syntax.
$query = "
UPDATE event
SET AssignedTo = '$AssignedTo',Project = '$Project',Category = '$EventCategory',
Status = '$Status',Services = '$EventServices',Priority = '$EventPriority',
WHERE EventID = '$ID' ";
try {
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex){ die( "Failed to run query: " . $ex->getMessage()); }
die("                      Changes Submitted");
}
This requires formatting the text, so it is too long for a comment.
If you format your queries neatly, then you can avoid or at least minimize such problems:
UPDATE event
SET AssignedTo = '$AssignedTo',
Project = '$Project',
Category = '$EventCategory',
Status = '$Status',
Services = '$EventServices',
Priority = '$EventPriority',
-------------------------------------^
WHERE EventID = '$ID';
The lines for the query don't scroll off the page, making it easier to spot an extra comma.