Python + MySQL: Search function returning all entries - python

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

Related

adding data to arrays in python with for loops from sql data return

I'm trying to add data to an array inside a loop as each row is column and row is returned.
my objective is to sort the columns into a few arrays but this does not appear to be working. i;ve been googling all afternoon about how to do this in python. W3 schools is demonstrating something like this but it wont work, nor will their simple array examples e.g. array[0] = "text" , and keeps returning errors that NameError: 'ReturnedUser_id' is not defined.
I then wish to pass these arrays out once i turn this code into a function.
Can anyone help me?
Thanks
import mysql.connector
mydb = mysql.connector.connect(
import mysql.connector
mydb = mysql.connector.connect(
host="xxx.xxx.xxx.xxx",
user="xxxxxxx",
passwd="xxxxxx",
database="vmware"
)
print(mydb)
mycursor = mydb.cursor()
mycursor.execute("select UserID, VMName, VMTemplate FROM VM WHERE CommissionStatus='commissioned';")
c = 0
for (User_id, VMName, VMTemplate) in mycursor:
c += 1
ReturnedUser_id[c] = User_id
ReturnedVMName[c] = VMName
ReturnedVMTemplate[c] = VMTemplate
To solve your problem with the current architecture you need to replace your logic with:
ReturnedUser_id = []
ReturnedVMName = []
ReturnedVMTemplate = []
for (User_id, VMName, VMTemplate) in mycursor:
ReturnedUser_id.append(User_id)
ReturnedVMName.append(VMName)
ReturnedVMTemplate.append(VMTemplate)
However I would do:
class VM:
def __init__(self, user_id, name, template):
self.user_id = user_id
self.name = name
self.template = template
#staticmethod
def from_row(row):
return VM(row[0], row[1], row[2])
all_vms = []
for row in mycursor:
all_vms.append(VM.from_row(row))
This allows you later to add more fiends and functionality in the VM class and instead of passing around three lists, you only pass one!

Python: Display table names, get user selection, display that table report from SQLite

I have a program that currently reads a database and it will print out the list of tables the current database has.
This is the DB LINK: database (Copy and Paste)
What I am trying to do now is to get user input to display the records from the specific table they chose. I am having trouble to get user selection to display the records. I am using SQLite3 as my main database software.
Also I am very aware of this question on here, but
I keep getting an error when I used the .format(category) embedded on my SQL.
sqlite3.ProgrammingError:
Incorrect number of bindings supplied.
The current statement uses 1, and there are 0 supplied.
This is what I have done so far:
import sqlite3
def get_data():
print("\nSelect a table: ", end="")
category = input()
category = str(category)
if '1' <= category <= '11':
print()
return category
else:
raise ValueError
def get_tables():
database = 'Northwind.db'
connection = sqlite3.connect(database)
c = connection.cursor()
sql = "SELECT * FROM sqlite_master WHERE type='table' AND NAME NOT LIKE 'sqlite_sequence' ORDER BY NAME "
x = c.execute(sql)
for row in x.fetchall():
table = row[1]
print(table)
def main():
category = get_data()
print(category)
get_tables()
if __name__ == "__main__":
main()
I hope this all makes sense. I appreciate the help.
Copy comment: My sql statement look like this:
*)multiple lines for readability
sql = ("SELECT * FROM sqlite_master
WHERE type='table'
AND Name = ?
AND NAME NOT LIKE 'sqlite_sequence'".format(category))
Your SQL string should be:
sql = """SELECT * FROM sqlite_master
WHERE type='table'
AND Name = ?
AND NAME NOT LIKE 'sqlite_sequence'"""
and the execute statement should be:
x = c.execute(sql, (category,))
also ensure that you are passing category as a parameter to your get_tables function.

How to Pass a Variable to SEARCH database in Python - Sqlite

I am trying to pass a variable to search for the row from SQLite DB and print out the results. Here is the code below thats causing the problem:
find_domain = 'domain.com'
def searchdomain(locate):
row = sql.execute("SELECT * FROM blocked_domains WHERE name = ?;",(locate,))
print(row)
searchdomain(find_domain)
No error comes up, it just come back blank.
Ensure that you have created a cursor object for data retrieval:
import sqlite3
conn = sqlite3.connect('tablename.db')
data = list(conn.cursor().execute("SELECT * FROM blocked_domains WHERE name = ?;", (locate,)))

Using Python to write to HTML file with MySQL data as source?

I am trying to generate some simple html pages that contain data stored in a MySQL database. I have searched and searched for an answer to this and while I can successfully generate html pages from txt or user input I can't get it working with SQL. I am not worried about formatting the data in html or anything, that I can work out. All I would like to do is something like the following but I can't work out how to actually get the data printing to the file. Any help would be greatly appreciated.
import MySQLdb
def data():
db_connection = MySQLdb.connect(host='localhost', user='root', passwd='')
cursor = db_connection.cursor()
cursor.execute('USE inb104')
cursor.execute("SELECT Value FROM popularity WHERE Category = 'movies'")
result = cursor.fetchall()
return result
htmlFilename = 'test.html'
htmlFile = open(htmlFilename, 'w')
htmlFile.write = data
htmlFile.close()
def data():
db_connection = MySQLdb.connect(host='localhost', user='root', passwd='')
cursor = db_connection.cursor()
cursor.execute('USE inb104')
cursor.execute("SELECT Value FROM popularity WHERE Category = 'movies'")
result = cursor.fetchall()
return ' '.join(result)
If your data() returns a tuple, you may want to use join to make it into a string.
Change this:
htmlFile.write = data
to:
def formatDataAsHtml(data):
return "<br>".join(data)
htmlFile.write(formatDataAsHtml(data()))
Make sure to replace
return ' '.join(result)
with
list_of_strings = ["(%s)" % c for c in result]
return ' '.join(list_of_strings)

TypeError: 'NoneType' object is not iterable

I need to process mysql data one row at a time and i have selected all rows put them in a tuple but i get the error above.
what does this mean and how do I go about it?
Provide some code.
You probably call some function that should update database, but the function does not return any data (like cursor.execute()). And code:
data = cursor.execute()
Makes data a None object (of NoneType). But without code it's hard to point you to the exact cause of your error.
It means that the object you are trying to iterate is actually None; maybe the query produced no results?
Could you please post a code sample?
The function you used to select all rows returned None. This "probably" (because you did not provide code, I am only assuming) means that the SQL query did not return any values.
Try using the cursor.rowcount variable after you call cursor.execute(). (this code will not work because I don't know what module you are using).
db = mysqlmodule.connect("a connection string")
curs = dbo.cursor()
curs.execute("select top 10 * from tablename where fieldA > 100")
for i in range(curs.rowcount):
row = curs.fetchone()
print row
Alternatively, you can do this (if you know you want ever result returned):
db = mysqlmodule.connect("a connection string")
curs = dbo.cursor()
curs.execute("select top 10 * from tablename where fieldA > 100")
results = curs.fetchall()
if results:
for r in results:
print r
This error means that you are attempting to loop over a None object. This is like trying to loop over a Null array in C/C++. As Abgan, orsogufo, Dan mentioned, this is probably because the query did not return anything. I suggest that you check your query/databse connection.
A simple code fragment to reproduce this error is:
x = None
for each i in x:
#Do Something
pass
This may occur when I try to let 'usrsor.fetchone' execute twice. Like this:
import sqlite3
db_filename = 'test.db'
with sqlite3.connect(db_filename) as conn:
cursor = conn.cursor()
cursor.execute("""
insert into test_table (id, username, password)
values ('user_id', 'myname', 'passwd')
""")
cursor.execute("""
select username, password from test_table where id = 'user_id'
""")
if cursor.fetchone() is not None:
username, password = cursor.fetchone()
print username, password
I don't know much about the reason. But I modified it with try and except, like this:
import sqlite3
db_filename = 'test.db'
with sqlite3.connect(db_filename) as conn:
cursor = conn.cursor()
cursor.execute("""
insert into test_table (id, username, password)
values ('user_id', 'myname', 'passwd')
""")
cursor.execute("""
select username, password from test_table where id = 'user_id'
""")
try:
username, password = cursor.fetchone()
print username, password
except:
pass
I guess the cursor.fetchone() can't execute twice, because the cursor will be None when execute it first time.
I know it's an old question but I thought I'd add one more possibility. I was getting this error when calling a stored procedure, and adding SET NOCOUNT ON at the top of the stored procedure solved it. The issue is that earlier selects that are not the final select for the procedure make it look like you've got empty row sets.
Try to append you query result to a list, and than you can access it. Something like this:
try:
cursor = con.cursor()
getDataQuery = 'SELECT * FROM everything'
cursor.execute(getDataQuery)
result = cursor.fetchall()
except Exception as e:
print "There was an error while getting the values: %s" % e
raise
resultList = []
for r in result:
resultList.append(r)
Now you have a list that is iterable.

Categories

Resources