Using PG14, Hikari pool, Kotlin 1.6
I get the following error when calling, for example, a SET query:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
val input = "yes"
connection.prepareStatement("SET log_connections TO ?")
.apply {
setString(1, input)
}.use {
it.execute()
}
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
Position: 22
at app//org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2675)
at app//org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2365)
at app//org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:355)
at app//org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:490)
at app//org.postgresql.jdbc.PgStatement.execute(PgStatement.java:408)
at app//org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:167)
at app//org.postgresql.jdbc.PgPreparedStatement.execute(PgPreparedStatement.java:156)
at app//com.zaxxer.hikari.pool.ProxyPreparedStatement.execute(ProxyPreparedStatement.java:44)
at app//com.zaxxer.hikari.pool.HikariProxyPreparedStatement.execute(HikariProxyPreparedStatement.java)
I'm trying to SET run-time configuration parameters of PostgreSQL from code by creating prepared statement and set its parameters safely, but I'm getting error while running such statement. Are there any limitations for creating prepared statements that might be limiting creation of such SET statement?
You can't pass a dynamic parameter using the SET command. You need to use the set_config() function:
val input = "yes"
connection.prepareStatement("select set_config('log_connections', ?, false)")
.apply {
setString(1, input)
}.use {
it.execute()
}
Related
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);
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 =.
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?
I'm trying to execute an sqlite code that delete all values from the table 'Categories"
Here is My code:
function deleteCATs() {
var db = LocalStorage.openDatabaseSync("Cat", "1.0", "Deleting Categories File", 1000000);
db.transaction(
function(tx) {
tx.executeSql('DELETE * FROM Categories');
//tx.executeSql('DELETE FROM Categories WHERE Category ="Cat"');
}
)
}
I'm getting the following error:
"Near "*": syntax error Unable to execute statement"
Any ideas on how this can be fixed? I'm using Qt Creator 3.0.0, Qt 5.2.0 Android version
The syntax is:
DELETE FROM Categories;
(The * is not necessary.)
Or, better yet in almost any database other than SQLite:
TRUNCATE TABLE Categories;
I am using SQL adapter in worklight where I need to have a variable that I need to use it in the query.
I read here and followed the same. But it`s showing the below error.
Pasted the complete error message on using a variable in the SQL adapter.
[ERROR ] FWLSE0099E: An error occurred while invoking procedure [project Sample]Device/SqlStatementFWLSE0100E: parameters: [project Sample]{
"arr": [
{
"parameters": [
null
],
"preparedStatement": "UPDATE devices SET DeviceQuantity=$[count] WHERE DeviceNames = 'DellTestLap';"
}
]
}
Parameter index out of range (1 > number of parameters, which is 0)..
Performed query:
UPDATE devices SET DeviceQuantity=$[count] WHERE DeviceNames = 'DellTestLap';
FWLSE0101E: Caused by: [project Sample]java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
com.worklight.common.log.filters.ErrorFilter
Project.js
function UpdateDeviceDetails(){
var count = 2;
var invocationData2 = {
adapter : 'Device', // adapter name
procedure : 'UpdateDeviceDetails', // procedure name
parameters : [count]
};
WL.Client.invokeProcedure(invocationData2,{
onSuccess : QuerySuccess,
onFailure : QueryFailure
});
}
Adapter.js
var DeviceDetails = WL.Server.createSQLStatement("UPDATE devices SET DeviceQuantity=$[count] WHERE DeviceNames = 'DellTestLap';");
function UpdateDeviceDetails(count) {
return WL.Server.invokeSQLStatement({
preparedStatement :DeviceDetails,
parameters : [count]
});
}
I've never used the $[variable_name] syntax with SQL adapters. I've always used "?"
"UPDATE devices SET DeviceQuantity=? WHERE DeviceNames =
'DellTestLap';"
However, assuming that this syntax does work, how is your code referencing the name "count"? The variable "count" is resolved as the number 2. The SQL statement won't be able to know to reference the name count just by the variable name. It would make more sense if the variable passed to parameters was more like this:
return WL.Server.invokeSQLStatement({
preparedStatement :DeviceDetails,
parameters : [{ count: 2 }]
});
That being said, I've never used this syntax before, I just use the "?" syntax.
You can also use the syntax of ?
var DeviceDetails = WL.Server.createSQLStatement("UPDATE devices SET DeviceQuantity=? WHERE DeviceNames ='DellTestLap';");
this will work surely try it !!!!!!!!!!!!!