0

I have a python script that interfaces with a mysql database i have. Each time i run it, it gives me a different error every time. I am becoming so confused as to what to do to fix it.

Basically, the code is meant for an user to input a search parameter for an account database, and the script searches a MySQL table and brings up data about the account.

As of now i get no errors, but it returns absolutely no search results.

I used to be able to make it search by an EXACT username, but i wanted it so you can search for a term within that username. Every attempt at the latter always results in some sort of error or i get no results back from MySQL.

import mysql.connector

users1 = mysql.connector.connect(
    host="localhost",
    user="python",
    passwd="HaHaYou'reNotGettingMyPassword",
    database="accounts"
)

cursor=users1.cursor()

usersearch = input("Please input the search term: ")

sql = ("SELECT user_id, username, date, status, description, gen FROM users1 WHERE username LIKE %s")
cursor.execute(sql, ('"' + usersearch + '"'))

result = cursor.fetchall()

for x in result:
    print(x)
print("In Order: User ID, Username, Account Creation Date, bla bla bla")

EDIT: i figured out i think my SQL syntax is incorrect. i'll try an fix that and see if that was my only problem.

2 Answers2

0

Try :


sql = ("SELECT user_id, username, date, status, description, gen FROM users1 WHERE username LIKE %s")
cursor.execute(sql, [usersearch])

altunyurt
  • 2,821
  • 3
  • 38
  • 53
0

If you get results when specifying a full username with the above, you probably need to add "wildcards" to your search term to "find within" existing strings. The wildcard "%" matches 0 or more characters.

E.g. change your string concatenation to:

cursor.execute(sql, ('"%' + usersearch + '%"'))

WARNING: This input style is wide open to SQL Injection Attack, as user input is directly used to create part of the SQL statement that is sent to the DB engine. Please see this answer for mitigation methods.

mgrollins
  • 641
  • 3
  • 9