Python MySql selecting from empty string - python

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

Related

escape character \quote is added when using salesforce query in 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

SELECT data from a DB given a WHERE clause from a listbox value

I am attempting to retrieve data associated given a particular last name. This last name, however, is stored within a listbox along with a first name and separator comma. As such, the name is retrieved from the listbox first by cursor selection, and only the last name is used to search by partitioning the rest:
lastname, sep, firstname = (self.patient_list.get(self.patient_list.curselection())).partition(',')
Once this is done, I am trying to get a printout of the data rows for this chosen last name. However, I am coming across the issue:
TypeError: argument 1 must be a string or unicode object: got tuple instead
I am wondering how to proceed with this issue. I have attempted a few solutions, such as the tuple function within the argument in load_query, as well as str on lastname, but it is a string...
I am also wondering if it is even necessary to select from a PostgreSQL db by this method. Can I try binding a listbox element to a row of data in the db? Or avoid partitioning the element, since that seems to be of trouble perhaps...
Full code:
def load_profile(self, event):
conn = pg.connect(user='postgres',
password='123!',
host='localhost',
port='5430',
database='carepartnerdb')
cur = conn.cursor()
#gets lastname from listbox, removes all else past the comma
#used to associate to DB
lastname, sep, firstname = (self.patient_list.get(self.patient_list.curselection())).partition(',')
load_query = (""" SELECT * FROM profiles_table WHERE patient_lastname=%s """, lastname)
cur.execute(load_query)
conn.commit()
#data = cur.fetchall()
#print(data)
cur.close()
conn.close()
load_query is a tuple, so cur.execute(load_query) will raise the exception as execute() expects a string (the query string) as the first argument.
You should change:
load_query = (""" SELECT * FROM profiles_table WHERE patient_lastname=%s """, lastname)
cur.execute(load_query)
to:
load_query = "SELECT * FROM profiles_table WHERE patient_lastname = %s"
cur.execute(load_query, (lastname,))
Also SELECT statement does not require commit().

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()

Python SQLite3 query concatenating two values

I have a database (student.db) that contains one table (Students).
Each row in students contains (ID, FName, LName).
There is an existing row (0, John, Doe).
I want to be able to enter a variable as a full name, find that name in the database, and delete that row.
Here's what I came up with... but it doesn't seem to work:
import sqlite3
conn = sqlite3.connect('student.db')
c = conn.cursor()
selection = "John Doe"
c.execute('DELETE FROM Students WHERE (FName + " " + LName =?', (selection,))
I don't get an error message. I'm guessing that's because it simply doesn't find any entries that match the WHERE clause.
Is there a way to properly write a WHERE clause that incorporates multiple values from the row of interest?
I am very new to this, so I apologize if this is a dumb question. I'm trying to make a Kivy app that creates a ListView of student names. Then you can select a student from the list and click "Delete" to remove that student from the ListView dictionary and from the database.
For concatenation most SQL implementations use '||' operator. See SQLite docs.
c.execute("DELETE FROM Students WHERE (FName || ' ' || LName = ?", (selection,))
Working with names is difficult but I think I'm over-thinking your question. Assuming that you just want to query two fields, you can split the name into a first_name and a last_name, and delete from the DB where that combination is satisfied.
selection = "John Doe"
first_name, last_name = selection.split()
query = """
DELETE FROM Students
WHERE FName = ? AND LName = ?
"""
c.execute(query, (first_name, last_name))
conn.commit()

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