-1
def search(title="",author="",year="",isbn=""):
    con = mysql.connector.connect(host="localhost", user="root", passwd="junai2104", database="book")
    cur = con.cursor()
    sql_statement = "SELECT * FROM book WHERE title={} or author={} or year={} or isbn={} ".format(title,author,year,isbn)
    cur.execute(sql_statement)
    rows=cur.fetchall()
    con.close()
    return rows    
print(search(title='test2'))

How can I search a value in MySQL using Python argument? how to get a values from the argument?

lospejos
  • 1,976
  • 3
  • 19
  • 35

1 Answers1

0

You have a couple of issues with your code:

  1. In your SQL SELECT statement you are looking for values in text columns (TEXT, VARCHAR etc.). To do so you must add single quotes to your search qriteria, since you want to indicate a text literal. So WHERE title={} should be WHERE title='{}' (same goes for the other parameters).
  2. When one or more of your arguments are empty, you will search for rows where the respective value is an empty text. So in your example search(title='test2') will trigger a search for an entry where the title column has the value 'test2' or any of the other three columns (author, year and isbn) has an empty text. If you inted to look for a title 'test2', this will only work if none of the other columns will ever contain an empty text. And even then, because of the three OR operators in your query, performance will be poor. What you should do instead is to evaluate each parameter individually and construct the query only with the parameters that are not empty.
  3. By constructing your query with formatting a string, you will create a massive security issue in case the values of your search parameters come from user input. Your code is wide open for SQL injection, which is one of the simplest and most effective attacks on your system. You should always parametrize your queries to prevent this attack. By general principle, never create SQL queries by formating or concatenating strings with their parameters. Note that with parametrized queries you do not need to add single quotes to your query as wriitten in point 1.
Sefe
  • 13,731
  • 5
  • 42
  • 55