Why aren't my SQL placeholders being replaced (using Go pq)? - sql

As per the docs, I'm doing this
var thingname string = "asdf";
var id int
err = database.QueryRow("SELECT id from things where thing = ?", thingname).Scan(&id)
but Postgres is saying
ERROR: syntax error at end of input at character 41
STATEMENT: SELECT id from things where thing = ?
I can't see that I'm doing much different to the demo code. I'm using pq.

The exact syntax is database dependent.
Use
err = database.QueryRow("SELECT id from things where thing = $1", thingname).Scan(&id)

Try this using $1 instead of ?:-
err = database.QueryRow("SELECT id from things where thing = $1", thingname).Scan(&id)

Related

EXPRESS and SQL "syntax error at or near "$""

I'm making PFP route with EXPRESS and PSQL and I have a little problem.
I get an error
Syntax error at or near "$"
Code:
if (!imgbbLink.startsWith("https://ibb.co/")) {
return res.status(400).json("Something went wrong")
}
await pool.query(
"UPDATE users SET user_profile_image = 1$ WHERE user_id = $2",
[imgbbLink, req.user.id]
)
res.json("PFP updated successfully")
I think there shouldn't be any problem?
Thanks.
You just made typo when indicated 1$ instead of $1:
UPDATE users SET user_profile_image = $1 WHERE user_id = $2

How to set large string as param without getting ORA-01460: unimplemented or unreasonable conversion error?

In spring-boot using namedParameterJdbcTemplate (Oracle db version 12 and odbc8 driver 12.2)
I am getting the following error while executing a SELECT query bound with a parameter larger than 4000 character whereas update queries working fine.
ORA-01460: unimplemented or unreasonable conversion requested
The unit test I am trying to execute;
#Test
public void testSqlSelectQueryLargeStringParameter() {
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("param", theLargeStr);
// #formatter:off
String sql =
"SELECT NULL id, NULL text FROM DUAL WHERE 'X' != :param ";
// #formatter:on
namedParameterJdbcTemplate.queryForRowSet(sql, params);
}
Is there any way to set this large param via MapSqlParameterSource?
I am #ahmet-orhan 's colleague, we've found a solution.
Thanks #kfinity for your suggestion, It is working for insert and update but we are still getting this error when we set clob or blob as "paremeter" in select statements.
If using a driver that supports JDBC4.0, the right solution is create a DefaultLobHandler and set streamAsLob or createTemporaryLob to true.
MapSqlParameterSource params = new MapSqlParameterSource();
String myString = "";
for (int i = 0; i < MAX_CLOB_BLOB_SIZE_IN_SELECT; i++) {
myString = myString + "1";
}
DefaultLobHandler lobHandler = new DefaultLobHandler();
lobHandler.setStreamAsLob(true);
params.addValue("param", new SqlLobValue(myString, lobHandler), Types.CLOB);
// #formatter:off
String sql =
"SELECT 1 id FROM DUAL WHERE :param IS NOT NULL ";
// #formatter:on
Integer id = namedParameterJdbcTemplate.queryForObject(sql, params, Integer.class);
We prefer streamAsLob but to be honest we have no idea which one is better.
This comment points out that ORA-01460 in JDBC queries is the same as "ORA-01704: string literal too long". (You can't have string literals longer than 4000 characters.) Maybe try this solution?
params.addValue("param", theLargeStr, Types.CLOB);
Although also != won't work for clob comparison, so you'll also need to change your query to
SELECT NULL id, NULL text FROM DUAL WHERE dbms_lob.compare('X',:param) != 0

Golang SQL query variable substituion

I have sql query that needs variable substitution for better consumption of my go-kit service.
I have dep & org as user inputs which are part of my rest service, for instance: dep = 'abc' and org = 'def'.
I've tried few things like:
rows, err := db.Query(
"select name from table where department='&dep' and organisation='&org'",
)
And:
rows, err := db.Query(
"select name from table where department=? and organisation=?", dep , org,
)
That led to error: sql: statement expects 0 inputs; got 2
Only hard-coded values work and substitution fails .
I haven't found much help from oracle blogs regarding this and wondering if there is any way to approach this.
Parameter Placeholder Syntax (reference: http://go-database-sql.org/prepared.html )
The syntax for placeholder parameters in prepared statements is
database-specific. For example, comparing MySQL, PostgreSQL, and
Oracle:
MySQL PostgreSQL Oracle
===== ========== ======
WHERE col = ? WHERE col = $1 WHERE col = :col
VALUES(?, ?, ?) VALUES($1, $2, $3) VALUES(:val1, :val2, :val3)
For oracle you need to use :dep, :org as placeholders.
As #dakait stated, on your prepare statement you should use : placeholders.
So, for completeness, you would get it working with something like:
package main
import (
"database/sql"
"fmt"
"log"
)
// Output is an example struct
type Output struct {
Name string
}
const (
dep = "abc"
org = "def"
)
func main() {
query := "SELECT name from table WHERE department= :1 and organisation = :2"
q, err := db.Prepare(query)
if err != nil {
log.Fatal(err)
}
defer q.Close()
var out Output
if err := q.QueryRow(dep, org).Scan(&out.Name); err != nil {
log.Fatal(err)
}
fmt.Println(out.Name)
}

coldfusion 9, params not found when using cfscript query

I am getting this error:
Parameter 'user_id AND league_id' not found in the list of parameters specified
I am passing them in, and I can see them in a dump placed inside the function.
here's whats going in...
ac = {
league_id = 1
,user_id = 3
,score1 = 14
,score2 = 10
};
this is the dump that is throwing the error....
writedump( Game.saveGame( argumentcollection = ac ) );
Here is the Game.saveGame function
public any function saveGame( required numeric league_id, required numeric user_id, required numeric score1, required numeric score2 ) {
// writeDump( var=arguments ); // this dump shows league_id & user_id...
var sql = '';
var tmp = '';
var r = '';
var q = new query();
q.setDatasource( this.dsn );
q.addParam(
name = 'league_id'
,value = '#val( arguments.league_id )#'
,cfsqltype = 'CF_SQL_BIGINT'
);
q.addParam(
name = 'user_id'
,value = '#val( arguments.user_id )#'
,cfsqltype = 'CF_SQL_BIGINT'
);
q.addParam(
name = 'score1'
,value = '#val( arguments.score1 )#'
,cfsqltype = 'CF_SQL_SMALLINT'
);
q.addParam(
name = 'score2'
,value = '#val( arguments.score2 )#'
,cfsqltype = 'CF_SQL_SMALLINT'
);
sql = 'INSERT INTO
games
(
user_id
,league_id
,score1
,score2
)
VALUES
(
:user_id
,:league_id
,:score1
,:score2
)
';
tmp = q.execute( sql = sql );
r = tmp.getPrefix( q );
q.clearParams();
return r;
}
Here is some history of the issue -
I am writing this locally and my system is running CF 11.2 - everything works fine... However, I had to host it on a CF 9.02 server, and that is when this error showed up - I cannot recreate it on my system although, I do recall seeing this error before, but for the life of me I cant find how I solved it then....
Any help or insight is appreciated.
Other params
Windows server, MySQL 5.5, Apache 2.2
Adam Wrote:
I can't spot what's wrong with your code, but you could perhaps clean
things up a bit. There's no need to set each "property" on the query
separately: blog.adamcameron.me/2014/01/
Following the ordinal param, instead of the named param, AND passing in the array of params in the condensed format, has solved my issue.
I may play with the name attribute and see if it is that, precisely.. or I may just deal with this as a solution.
Now, to change all my script queries!!!!!
(I wish his article came up on google, when I was looking into the query.cfc syntax. :(
Thanks a bunch Adam!

Showing the result of a query

I'm trying to build a query to get the numbers of rows that have the same data on a column (my column is ESTADO).
var db = Database.Open("MyDB");
var selectedData = db.Query("SELECT COUNT (*) FROM graficos WHERE ESTADO='FECHADO'");
var data = db.QueryValue(selectedData);
But when i try to run it gives the following error:
Compiler Error Message: CS1502: The best overloaded method match for 'WebMatrix.Data.Database.QueryValue(string, params object[])' has some invalid arguments
Line 51: var data = db.QueryValue(selectedData);
Pass the query directly to the QueryValue() method.
var data = db.QueryValue("SELECT COUNT (*) FROM graficos WHERE ESTADO='FECHADO'");
Read this documentation for more information on how to use the Database.QueryValue() method.