escape character \quote is added when using salesforce query in python - python

I am trying to query salesforce object from python .
the query string contains 'single quote so escape characters added automatically
and it failed because \backslash escape character added in the query
name=David's
sql_query = (
f"SELECT Id FROM contact WHERE Name = '{name}'"
)
Expected string output:
sql_query = SELECT Id FROM contact WHERE Name = 'David's'
Actual string formed by script
sql_query = SELECT Id FROM contact WHERE Name = 'David\'s'
Any help pls

You need to put your name string variable in double quotes. Additionally, the way you are inserting name into the sql_query string is not correct.
Try this:
name = "David's"
sql_query = "SELECT Id FROM contact WHERE Name = " + name

Related

Problem in Where clause of SQL Query while comparing String using python variable

Im trying to select from MS Access Database table in python WHERE Itemname is equal to some particular string which is stored in variable , while comparing that string directly in where clause with LIKE operator it is working fine but when i`m trying to pass this string through variable it is showing me syntex error.
query = "SELECT * FROM table1 WHERE table1.Itemname LIKE 'XYZ' "
cursor2.execute(query)
This is working fine
Itemname = "XYZ"
query = "SELECT * FROM table1 WHERE table1.Itemname LIKE %s "
cursor2.execute(query,(Itemname,))
Itemname = "XYZ"
query = "SELECT * FROM table1 WHERE table1.Itemname LIKE {}".format(Itemname)
cursor2.execute(query)
None of the Two above options are working ,Pls point out if there is any syntex problem
This is working finally
Itemname = "XYZ"
query = "SELECT * FROM table1 WHERE table1.Itemname = ? "
cursor2.execute(query,[itemname])

Python MySql selecting from empty string

I'm trying to select from a table so that the parameter I input can be nothing but it still will select everything
name = ""
mycursor.execute('SELECT * FROM table WHERE name LIKE "%%%s%%"' (name, ))
I was hoping to have if name is something like "", then everything in the table will be fetched.
With LIKE it will not be possible , however you can achieve it using REGEXP
name = "John Doe"
regexp='^.*$'
value = (regexp if name=="" else name)
query = "SELECT * FROM mysql.user WHERE name REGEXP '{}' ;".format(value)
print(query)
Note: However be wary that if you are looking for a single user, and if there are other user names that matches the string Like "John Doe1" it will return both the entries

Spare apostrophe sign in SQL query in SQLAlchemy

I am trying to search for a book in the database so I first check if the data informed by the user (can be the title, ISBN or author's name) exists in the DB then I check if part of the data exists and, finally I return all the results.
To do so I wrote this code in Python using SQLAlchemy and FLASK where
searchBy is the name of the column in the DB and
searchFor is the data the user input
.
books = db.execute(f"SELECT * FROM books JOIN authors ON books.author_id = authors.id \
WHERE ({searchBy} = :searchFor) OR ({searchBy} LIKE :searchFor%)",
{"searchFor": searchFor}).fetchall()
However, when :searchFor is replaced by its corresponding value, it is outputed between aphostropes.
...(title = 'Animal Farm') OR (title LIKE 'Animal Farm'%)
causing this error
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) syntax error at or near ")"
LINE 1: ... WHERE (title = 'Love') OR (title LIKE 'Love'%)
^
Can anyone help me to understand why this is happening and how to correctly do it?
The reason that is happening is because it is passing the variable as a string (as it should in this instance). Knowing this, you'll want to concatenate the % symbol with the search string. Something like this should work:
books = db.execute(f"SELECT * FROM books JOIN authors ON books.author_id = authors.id \
WHERE ({searchBy} = :searchFor) OR ({searchBy} LIKE (:searchFor || '%'))",
{"searchFor": searchFor}).fetchall()

Add a single quote to a string in Python 2.7

I want to use an SQL output string to query some data in PostgreSQL using Python. I'm using Python 2.7.
For example:
The output string is mike
I want to have mike as 'mike' to be valid as an input.
This is my code:
formated_fix_names = ''.join(author_name_fix_list)).replace(' ', '\'')
The problem is I need to pass this string to an SQL code as name = 'mike':
cursor.execute("select author_name from commits where commit_hash in ("+formated_fix_names+")")
The problem must be at this part I think .replace(' ', '\'').
Do not mess with string manipulation. Psycopg does the right thing by adapting a Python list to a Postgresql array:
author_list = ['John','Mary']
query = """
select author_name
from commits
where commit_hash = any (%s)
"""
print cursor.mogrify(query, (author_list,))
#cursor.execute(query, (author_list,))
Output:
select author_name
from commits
where commit_hash = any (ARRAY['John', 'Mary'])
Notice that the list must be passed to the cursor.execute method wrapped in an iterable.
The in syntax can be used if the list is cast to a tuple:
author_list = ['John','Mary']
query = """
select author_name
from commits
where commit_hash in %s
"""
print cursor.mogrify(query, (tuple(author_list),))
#cursor.execute(query, (tuple(author_list),))
Output:
select author_name
from commits
where commit_hash in ('John', 'Mary')
If you want to turn the string mike into the string 'mike' you can use this expression:
name = "mike"
newName = "'%s'" % name
This turns name, which contains the string mike, into newName, which contains the string mike with single quotes around it, which you should now be able to use. I hope this helps!
You can use double quotes(""), for example:
name = "mike"
result = "'" + name + "'"

mysql.connector select query with binary values

Using Python's mysql.connector, how can I select all records that match a tuple?
For example:
ids = (b'6TRsHMzWSrq0zeembo0Vbg',
b'7Qoq53lKTk-RZOi830t3MA',
b'7ZGO9S3DTcGHjwrfpV0E0A')
And then the query would do something like:
query = SELECT first_name
FROM users
WHERE id = (ids)
Returning records for all users whose ID appears in the tuple
Try doing this
query = "SELECT first_name FROM users WHERE id IN " + str(list(ids))
cursor.execute(query)
On second thoughts, the following should also work
query = "SELECT first_name FROM users WHERE id IN " + str(ids)
EDIT
OP mentions in comments that the ids are binary data returned from a previous query. In which case, taking hint from this answer and using BINARY operator, the following query should work
query = "SELECT first_name FROM users WHERE BINARY id IN " + str(ids) ;

Categories