Hi I have the following block of code that is meant to take the variable 'search_value'and pass it into the WHERE clause of a mysql select statement
import MySQLdb
search_term = input('Enter your search term: ')
print (search_term)
conn = MySQLdb.connect(my connection info)
c = conn.cursor()
q = "SELECT * FROM courses WHERE course_area = %(value)s "
params = {'value': search_term}
c.execute(q, params)
rows = c.fetchall()
for eachRow in rows:
print (eachRow)
I know that I need to use %s somewhere but I'm not sure of the exact syntax. I did some searching online but I have only found examples of insert statement...and I know they have a little different syntax. Thanks
This should work:
q = "SELECT * FROM courses WHERE course_area = %(value)s "
params = {'value':'some_value_here'}
c.execute(q, params)
.....
Related
I'm putting together an inventory program using Python and MySQL. I want to implement a search function that returns entries based on user input (programmed in a separate GUI file). In the code below, I expected that the search function would return entries with the brand "UGreen". Instead, it returns all of the entries in the table.
I'm not sure what I'm doing wrong here. I have used a similar structure in another program with a sqlite database instead and the search worked fine.
Any and all help/suggestions would be greatly appreciated :)
import mysql.connector
equipdb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "REDACTED",
database = "tel_inventory"
)
def view():
cur = equipdb.cursor()
cur.execute("SELECT * FROM equipment")
result = cur.fetchall()
return result
def search(name="", brand="", model="", consumables="", storage="", room="", photo=""):
cur = equipdb.cursor()
cur.execute("SELECT * FROM equipment WHERE name=%s OR brand=%s OR model=%s OR consumables=%s OR storage=%s OR room=%s OR photo=%s", (name, brand, model, consumables, storage, room, photo))
result = cur.fetchall()
return result
#print(view())
print(search(brand="UGreen"))
Try using keyword argument directly
def search(**kwargs):
cur = equipdb.cursor()
key = str(list(kwargs.keys())[0])
value = str(kwargs[key])
cur.execute('SELECT * FROM equipment WHERE {} = "{}"'.format(key,value))
result = cur.fetchall()
return result
I have an Entry box on my search page. I want this function to search the table (movies) in my database for whatever text (column name is 'title') was entered into that Entry box, and then display the result.
def search_now():
conn = sqlite3.connect('movie_catalog.db')
c = conn.cursor()
searched = search_box.get()
sql = "SELECT * FROM movies WHERE title = %s"
name = (searched, )
result = c.execute(sql, name)
if not result:
result = "Movie not found"
# Commit our changes
conn.commit()
# Close database connection
conn.close()
I keep getting the following error message:
sqlite3.OperationalError: near "%": syntax error
The tutorial I've been using is using MYSql, so I'm not sure if the "%s" placeholder applies or not. Any ideas?
you should either do this (not safe)
searched = search_box.get()
sql = "SELECT * FROM movies WHERE title = '%s'" % searched
result = c.execute(sql)
or this (fairly secure against injections)
searched = search_box.get()
t = (searched,)
sql = "SELECT * FROM movies WHERE title=?"
result = c.execute(sql, t)
EDIT:
In your example you are passing the literal string SELECT * FROM movies WHERE title = '%s'" to the database, this is why it is complaining about the %s
hi i am looking to insert these 3 values into my SQL database table that has columns: email, cardnumber, dateandtime
here is my code:
email = input("Email: ")
cardnumber = int(input("Enter card number:"))
now = datetime.now()
now = now.strftime('%Y-%m-%d %H:%M:%S')
newrowforsql()
my code for the query is:
def newrowforsql():
query = """\
insert into table1 (email,cardnumber,dateandtime)
values(email,cardnumber,now)"""
insertnewrow = execute_query_commit(conn, query)
I cant seem to insert the values
my code for executing the query and committing it is:
def execute_query_commit(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
connection.commit()
print("Query executed and committed")
except pyodbc.Error as e:
print(f"The error '{e}' occurred")
As "azro" mentioned correctly you didn't put in the variable content to the query, you just put in the name of the variable which contains the information you want. What you need to change is the following:
def newrowforsql():
query = """\
insert into table1 (email,cardnumber,dateandtime)
values(email,cardnumber,now)"""
insertnewrow = execute_query_commit(conn, query)
to
def newrowforsql():
query = """\
insert into table1 (email,cardnumber,dateandtime)
values({theEmail},{theCardnumber},{now})""".format(theEmail=email, theCardnumber=cardnumber, now=now)
insertnewrow = execute_query_commit(conn, query)
This is one of the most used options to manipulate strings in python. But if you are using python3.7+ (maybe from Python3.6 and up, but I'm not sure) there is a much better and faster option to manipulate strings, it's name is "f-strings".
Here is the same solution but with f-strings instead of the method str.format
def newrowforsql():
query = f"""\
insert into table1 (email,cardnumber,dateandtime)
values({email},{cardnumber},{now})"""
insertnewrow = execute_query_commit(conn, query)
Good luck!
I want to search a mysql table for rows where the specified column has a particular value. For example, given the input string memory=2048 it will search for the rows that have "2048" as the value of memory column and it will print them.
This is code that I have tried but it print outs nothing.
input = input()
tag = input.split("=")
desc = tag[1]
tag = tag[0]
mycursor = mydb.cursor()
sql = "(SELECT * FROM comp WHERE %s LIKE %s)"
val = (tag, desc)
mycursor.execute(sql, val)
res = mycursor.fetchall()
for x in res:
print(x)
Secondly I tried this code to see where is the problem :
input = input()
tag = input.split("=")
desc = tag[1]
tag = tag[0]
mycursor = mydb.cursor()
sql = "(SELECT * FROM comp WHERE memory LIKE '2048')"
mycursor.execute(sql)
res = mycursor.fetchall()
for x in res:
print(x)
It gives the desired output. So my problem is when I am trying to get the column name with %s it comes as 'memory' and It couldn't finds it, since the name of the column is memory. Is there a way to get rid of the '' chars ?
confirmation of inputs
Looking at the mysql.connector's execute() documentation it appears to use %s as placeholders for bind parameters.
So your execute("SELECT * FROM comp WHERE %s LIKE %s", ("memory", "2048")) call ends up running like the following SQL:
SELECT * FROM comp WHERE 'memory' LIKE '2048'
obviously returning 0 rows.
You need to put the literal column name into the query text before invoking execute():
sql = "SELECT * FROM comp WHERE %s LIKE %s" % (tag, "%s")
# => "SELECT * FROM comp WHERE memory LIKE %s"
mycursor.execute(sql, (desc, ))
Good day all. Lurking here has been a great help - thanks in advance.
What I'd like to do is accept an input from the user, then search both the 'type' and the 'count' columns of the 'mytable' table for anything that matches the user's input.
Here's my code:
import sys
import sqlite3 as lite
for arg in sys.argv:
print arg
var = raw_input("What are you looking for: ")
print "Standby; looking for : ", var
vart = '%'+var+'%' # to add wildcards to the var string
con = lite.connect('test.db')
print
print "Ok. Here's what I found."
print
with con:
cur=con.cursor()
cur.execute( "SELECT * FROM mytable" )
# cur.execute( "SELECT * FROM mytable WHERE type LIKE ( ? )", [vart]) # this actually works - but only searches type column
# cur.execute( "SELECT * FROM mytable WHERE type LIKE ( ? ) OR WHERE count like ( ? )", [vart], [vart] ) fails
# cur.execute( "SELECT * FROM mytable WHERE type LIKE ( ? ) UNION ALL SELECT * FROM mytable WHERE count LIKE ( ?)", [vart], [vart])
rows = cur.fetchall()
# now row has each line to deal with
#print len(rows) #prints the number of lines in the db
for row in rows:
#print len(row) # prints the number of items in the list
# if var in row[0]... then print
mstr=row[0]
print mstr.encode('ascii'), row[1]
Here is the puny database:
type : count
fox|23
dog|34
cat|99
bird|123
rat|201
mouse|23
hedgehog|44
gnu|666
I was successful at searching one column only for the input string, but when I try to do both columns at once, it fails. There's got to be a way that using the sqlite3 functions and not rely on the python ones.
A valid un-nested SQL SELECT statement only has one WHERE statement; also, if you're passing multiple parameters to a sqlite cursor, they must be contained in a single list. The correct syntax for your code would be:
cur.execute('SELECT * FROM mytable WHERE type LIKE ( ? ) OR count like ( ? )', [vart, vart])
just a little syntax fix, and I spruced up your python to be more pep8 friendly (and closer to python3 support, although raw_input is not native in python3). From that you should be able to expand....
import sys
import sqlite3 as lite
'''
made your code more pep8 python like
note comments in python are reserved for
why not what..e.g. code is self descriptive
of what, but why is what is important
'''
print('{}'.format(sys.argv)) # debug
var = raw_input("What are you looking for: ")
print("Standby; looking for :{}".format(var))
vart = '%{}%'.format(var)
con = lite.connect('test.db')
print("\nOk. Here's what I found.\n")
with con:
cur = con.cursor()
sql_query = 'SELECT * FROM mytable WHERE type LIKE ? or count LIKE ?'
cur.execute(sql_query, ['%{0}%'.format(var), '%{0}%'.format(var)])
try:
rows = cur.fetchall()
except Exception as err:
print(err)
for row in rows:
mstr = row[0]
print('Found: {} : {}'.format(mstr.encode('ascii'), row[1]))
output examples
host-wifi:java user$ python /tmp/p.py
['/tmp/p.py']
What are you looking for: 99
Standby; looking for :99
Ok. Here's what I found.
Found: cat : 99
host-wifi:java user$ python /tmp/p.py
['/tmp/p.py']
What are you looking for: 3
Standby; looking for :3
Ok. Here's what I found.
Found: fox : 23
Found: dog : 34
Found: bird : 123