I'm getting an error on a simple statement through PG:
require 'pg'
conn = PG.connect( dbname: 'myDB' )
#res = conn.exec_params( 'SELECT count(id) FROM users WHERE username = $1 AND status = "active"', ['johnny5'] )
The error:
/Users/rich/app.rb:14:in `exec_params': ERROR: column "active" does not exist (PG::UndefinedColumn)
LINE 1: ...unt(id) FROM users WHERE username = $1 AND status = "active"
^
"active" is a field value, not a column.
My question: I have fixed this by entering the value "active" as another placeholder. Are quoted values in the SQL not permitted? I assumed that quoted aspects of the SQL would have been fine.
String literals in SQL use sigle quotes, double quotes are for identifiers (such as table and column names). So, when you mention "active", the database complains that there is no such column.
The solution is to use a placeholder:
#res = conn.exec_params(
%q{SELECT count(id) FROM users WHERE username = $1 AND status = $2},
['johnny5', 'active']
)
or use single quotes inside the SQL:
#res = conn.exec_params(
%q{SELECT count(id) FROM users WHERE username = $1 AND status = 'active'},
['johnny5']
)
Switching from '...' to %q{...} for your SQL string literal makes the internal quoting problems a bit easier to deal with.
Related
I want to execute a command using pyodbc in my Django app. When I do simple update with one column it works great:
cursor.execute("UPDATE dbo.Table SET attr = 1 WHERE id = {}".format(id))
However when I try to use a string as a column value it throws error:
cursor.execute("UPDATE dbo.Table SET attr = 1, user = '{}' WHERE id = {}".format(id, str(request.user.username)))
Here's error message:
('42S22', "[42S22] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name 'Admin'. (207) (SQLExecDirectW)")
Suprisingly this method works:
cursor.execute("UPDATE dbo.Table SET attr = 1, user = 'Admin' WHERE id = {}".format(id))
What seems to be the problem? Why is sql mistaking column value for its name?
As mentioned above, you have your arguments backwards, but if you're going to use cursor.execute(), the far more important thing to do is use positional parameters (%s). This will pass the SQL and values separately to the database backend, and protect you from SQL injection:
from django.db import connection
cursor = connection.cursor()
cursor.execute("""
UPDATE dbo.Table
SET attr = 1,
user = %s
WHERE id = %s
""", [
request.user.username,
id,
])
You've got your format arguments backwards. You're passing id to user, and username to the id WHERE clause.
I am using a RESTful API with Node.js/Express and a PostgreSQL database ( PostgreSQL version is 12.4). I'm not using an ORM just straight SQL. I am trying to create a "SELECT CASE" statement but I keep running into errors. The error messages I am getting are "confirmed_member is not a column". Can anyone see what is wrong with my syntax here:
var query = ['SELECT *, CASE WHEN confirmed = true THEN "confirmed_member" ELSE "pending" END AS "status" FROM members WHERE groupid = $1']
try {
const member = await pool.query(query, [groupid]);
res.status(200).json(member.rows)
} catch (err) {
res.status(400).json({ message: err.message })
}
Note: The query works fine in Valentina DB.
EDIT: In response to answers below, I switched to double quotes because this was the error I was getting in the IDE when I used single quotes
Use single quotes for string literals in SQL. Some flavors of SQL (e.g. SQLite) also accept double quotes, but you should not rely on this behavior.
var query = ["SELECT *, CASE WHEN confirmed = true THEN 'confirmed_member' ELSE 'pending' END AS status FROM members WHERE groupid = $1"];
You need to use single quote for the literals as follows:
SELECT *,
CASE WHEN confirmed = true THEN 'confirmed_member' ELSE 'pending' END AS "status"
FROM members WHERE groupid = $1
For anyone who comes across the same issue: I got it working by enclosing the SQL statement in double quotes and escaping the double quotes for the column name.
var query = ["SELECT *, CASE WHEN confirmed = true THEN 'confirmed_member' ELSE 'pending' END AS \"status\" FROM members WHERE groupid = $1"]
I have a SQL query entered into a constant. One of the fields that I need to put in my where clause is USER which is a key word. To run the query I put the keyword into double quotes.
I have tried all of the suggestions from here yet none seem to be working.
Here is what I have for my constant:
SELECT_USER_SECURITY = "SELECT * FROM USER_SECURITY_TRANSLATED WHERE \"USER\" = '{user}' and COMPANY = " \
"'company_number' and TYPE NOT IN (1, 4)"
I am not sure how to get this query to work from my constant.
I also tried wrapping the whole query in """. I am getting a key error on the USER.
SELECT_USER_SECURITY = """SELECT * FROM USER_SECURITY_TRANSLATED WHERE "USER" = '{user}' and
COMPANY = 'company_number' and TYPE NOT IN (1, 4)"""
Below is the error I am getting:
nose.proxy.KeyError: 'user'
So the triple quoted solution was the best one. The problem I was running into was I had not included the "user" key in my dictionary of params which formatted the query.
I'm trying to write an write this:
Team.last.players.sum("goals")
erb:
SELECT SUM("players"."goals")
FROM "players"
WHERE "players"."team_id" = $1 [["team_id", 2]]
how to rewrite this so that I could use it in a method:
def sql_search
sql = "SELECT SUM \"players\".\"goals\" FROM \"players\" WHERE \"players\".\"team_id\" = $1 [[\"team_id\", #{self.id}"
connection.execute(sql);
end
keep getting this error:
PG::SyntaxError: ERROR: syntax error at or near "."
LINE 1: SELECT SUM "players"."goals" FROM "players" WHERE "players"....
Any ideas would be appreciated
You don't need to add \" in sql statement, just remove them.
def sql_search
sql = "SELECT sum(goals) FROM players WHERE team_id = #{self.id};"
connection.execute(sql);
end
Is there some reason that you want to hard code the SQL query? It's generally bad practice to use string interpolation to insert parameters to SQL queries because of SQL injection attacks. Instead it's recommended to use ActiveRecord's SQL query parameter binding like this:
user_input = 5
Player.where('team_id = ?', user_input).sum(:goals)
Basically what this does is insert the parameter 5 after sanitization. This means you're safe from attacks where a hacker attempts to insert arbitrary SQL into parameter variables attempting to return sensitive data or delete data entirely!
I am trying to run perl script but i get an oracle error.
DBD::Oracle::db prepare failed: ORA-01756: quoted string not properly terminated (DBD ERROR: OCIStmtPrepare)
But this SQL QUERY perfectly works fine in TOAD
MY perl connection details:
my $dbh = DBI->connect($dsn, $dbuser, $dbpass, { RaiseError => 1, AutoCommit => 0 });
my $sth=$dbh->prepare($SQL);
$sth->execute or die "EXEC ERROR $sth->errstr";
sql query:
SELECT name FROM employee WHERE
event IN ('IPO', 'RIGHTS')
AND (NOT market_code = 'ID' OR NOT event = 'RIGHTS')
AND NOT market_code = 'IN'
AND NOT market_code = 'NZ'
AND name NOT LIKE '%stat%'
AND NOT REGEXP_LIKE (name, 'S.K(Q|S)$')
AND name NOT LIKE '.%'
AND name NOT LIKE '%ol.SI'
AND name NOT LIKE '%bi.SI'
Perl will interpolate double-quoted string literals, like
my $SQL = "REGEXP_LIKE (name, 'S.K(Q|S)$')";
In here, your "variable" $' will be replaced with its value.
If you don't want that, use a non-interpolating version:
my $SQL = q{REGEXP_LIKE (name, 'S.K(Q|S)$')};
Single-quoted strings would also do, but since you have single quotes inside, the q{} is convenient. You can choose any terminator you want (such as q[]) and you can make it interpolate, too, with qq{}.