Passing a variable string to LIKE in SQLite (Python) - python

So I've been looking around but I can't seem to find answer to a seemingly simple and probably commonly asked question. In SQLite, I have a query that I want to pass via user defined search text.
search = xChatMessageSplit[2]
c.execute("SELECT * FROM captured WHERE Nick=? AND Name LIKE '%search%'",(xChatNick,search))
Obviously the syntax or whatever is incorrect since I'm getting errors, but I want to basically allow users to define a search term for string, "search." How would I go about doing this? I tried using REGEXP but I can't seem to figure out how to define the function so I figured I'd just go with LIKE since it's already implemented into SQLite3

You need to use ? to show where the parameter's value will be used.
c.execute("""SELECT * FROM captured
WHERE Nick=?
AND Name LIKE ('%' || ? || '%')""", (xChatNick,search))

Related

How to search for values in TinyDB

I would like to search my database for a value. I know you can do this for a key with db.search() but there does not seem to be any kind of similar function for searching for a value
I've tried using the contains() function but I have the same issue. It checks if the key is contained in the database. I would like to know if a certain value is contained in the database.
I would like to do something like this that would search for values in tinydb
db.search('value')
If I was able to execute the above command and get the value(if it does exist) or Nothing if it doesn't that would be ideal. Alternatively, if the able returned True or False accordingly, that would be fine as well
I don't know if this is what you are looking for but which the following command you can check for a specific field value:
from tinydb import Query
User = Query()
db.search(User.field_name == 'value')
I'm new here (doing some reading to see if TinyDB would even be applicable for my use case) so perhaps wrong, and also aware that this question is a little old. But I wonder if you can't address this by iterating over each field and searching within for your value. Then, you couldget the key or field wherein a value match was located.

Python Formatting SQL WHERE clause

I'm having this function that communicates via pymysql to an SQL database stored to my localhost. I know there are similar posts about formatting an SQL section especially this one but could anyone suggest a solution?
Always getting TypeError: can't concat tuple to bytes. I suppose it's sth with the WHERE clause.
def likeMovement(pID):
print("Give a rating for the movement with #id:%s" %pID)
rate=input("Give from 0-5: ")
userID=str(1)
print(rate,type(rate))
print(pID,type(pID))
print(userID,type(userID))
cursor=con.cursor()
sqlquery='''UDPATE likesartmovement SET likesartmovement.rating=%s WHERE
likesartmovement.artisticID=? AND likesartmovement.userID=?''' % (rate,),
(pID,userID)
cursor.execute(sqlquery)
TypeError: not all arguments converted during string formatting
Thanks in advance!
The problem is that you're storing (pID,userID) as part of a tuple stored in sqlquery, instead of passing them as the arguments to execute:
sqlquery='''UDPATE likesartmovement SET likesartmovement.rating=%s WHERE
likesartmovement.artisticID=? AND likesartmovement.userID=?''' % (rate,)
cursor.execute(sqlquery, (pID,userID))
It may be clearer to see why these are different if you take a simpler example:
s = 'abc'
spam(s, 2)
s = 'abc', 2
spam(s)
Obviously those two don't do the same thing.
While we're at it:
You have to spell UPDATE right.
You usually want to use query parameters for SET clauses for exactly the same reasons you want to for WHERE clauses.
You don't need to include the table name in single-table operations, and you're not allowed to include the table name in SET clauses in single-table updates.
So:
sqlquery='''UDPATE likesartmovement SET rating=? WHERE
artisticID=? AND userID=?'''
cursor.execute(sqlquery, (rating, pID, userID))

Using like statement in python 2.6

I am trying to extract the names from the db that have A in the second position.
In sql it's simple but python sees the '_A%' as end of query.
Has anyone faced this problem before and came out with a solution?
I saw a similar question and the accept result was to use '% %' instead of ' %', but this didn't worked.
This is my query:
def queryDelivery(start_date):
query_basictable = """
SELECT Code,Quantity, Datetime
FROM Mytable
WHERE Datetime>= '%s 12:00:00' AND Name LIKE '_A%'
""" %(start_date)
delivery_data= pd.read_sql(sql=query_basictable, con=engine)
return delivery_data
I was thinking about passing the symbol '_A%' to a variable and the do something like a substitute but when try to assign the symbol hits syntax error
variable = ''_A%' '
Name LIKE variable
How can I do this in a clean way?
Don't do it this way. As soon as you do this, if someone inserts a start_date like "'; drop table students; --" you have a problem.
I tested placeholders in Python 2.7 and it looks like you don't run into the problem until you use the % operator.
A much better way is to write your SQL statements in a way that every value passed in can be used in a placeholder. Then use placeholder syntax and the syntax becomes LIKE ? || '%'

Using variable combining LIKE and %s% in SQLite and Python

Using:
Python3
SQLite
TKinter
I am currently trying to create a function to search for a keyword in a database, but as soon as I try to combine it with TKinter, it seems to fail.
Here are the relevant lines:
(I tried it in a lot of different ways, those 3 lines below seem to work with variables, but not with the input from TKinter, so I thought they might actually work, if I edit them a little.
The problem I got is, that I'm not experienced in TKinter and SQLite yet and worked with those 2 for about 3 days yet.
def searcher(column):
#Getting input from user (TKinter)
keyword = tk.Entry(self)
keyword.pack()
#Assigning the input to a variable
kword = keyword.get()
c.execute("SELECT * FROM my_lib WHERE {kappa} LIKE {%goal%}".format(kappa=column, goal=kword))
#c.execute("SELECT * FROM my_lib WHERE "+column+"=?", (kword,))
#c.execute("SELECT * FROM my_lib WHERE {} LIKE '%kword%'".format(column))
I want to check if any of the data CONTAINS the keyword, so basically:
k_word in column_data
and not
column_data == k_word
My question is:
Is there a way to take the user input (by TKinter) and search in the database (SQLite) and check, if any data in the database contains the keyword.
The SQLite docs explain that you can use ? as a placeholder in the query string, which allows you so substitute in a tuple of values. They also advise against ever assembling a full query using variables with Python's string operations (explained below):
c.execute("SELECT * FROM my_lib WHERE ? LIKE ?", (column, '%'+kword+'%'))
You can see above that I concatenated the % with kword, which will get substituted into the second ?. This also is secure, meaning it will protect against SQL Injection attacks if needed.
Docs: https://docs.python.org/2/library/sqlite3.html
Related posts: Escaping chars in Python and sqlite
Try:
kword = "%"+kword+"%"
c.execute("SELECT * FROM my_lib WHERE kappa LIKE '%s'" % kword)
After trying over and over again, I got the actual solution. It seems like I can't just add the '%' to the variable like a string, but rather:
c.execute("SELECT * FROM my_lib WHERE {} LIKE '%{}%'".format(column, kword))

sqlite3 python query with multiple variables error

I looked all over for the answer to my question and could not find any good answer.... I am using python with the sqlite3 module to query a database. The problem is that I cannot get a sql query to hold multiple variables. For example...
I can get this query to work perfectly. ("wordsofar" is the variable name)
c.execute("SELECT word FROM wordlist WHERE word LIKE ?", wordsofar)
However I cannot get this code to work. ("wordsofar" and "noletter" are the variable names)
c.execute("SELECT word FROM wordlist WHERE word LIKE ? AND word NOT LIKE ?", (wordsofar, noletter))
It gives me the error: "Error binding parameter 0"
I have tried to rewrite the query so instead of "?" it is using the named convention such as shown by http://docs.python.org/py3k/library/sqlite3.html (about half way down the page) but that did not solve the problem.
Any help would be much appreciated. Thank-you!
This line (that you say works) shows that wordsofar is a sequence of one element:
c.execute("SELECT word FROM wordlist WHERE word LIKE ?", wordsofar)
In this case the second line should be:
c.execute("SELECT word FROM wordlist WHERE word LIKE ? AND word NOT LIKE ?",
wordsofar + (noletter,))
If noletter is a string and wordsofar is a tuple (as you say in your comment).
execute() docs say that the second argument is always parameters. If you use '?' then number of parameters (len(parameters)) is equal to number of '?' in the sql statement.
You code looks fine.
The problem is in the data. Either wordsofar or noletter is an object that sqlite3 doesn't know how to store.
One solution is to pickle the object. Another solution is to supply converter and adapter functions.
Use register_adapter to register a callable to convert the custom Python type type into one of SQLite’s supported types.
The docs also describe how to supply converters to handle the reverse conversion:
SQLite natively supports only the types TEXT, INTEGER, FLOAT, BLOB and
NULL. If you want to use other types you must add support for them
yourself. The detect_types parameter and the using custom converters
registered with the module-level register_converter() function allow
you to easily do that.
Here's a related SO question with answers.

Categories

Resources