On a CentOS Linux system, I have a MariaDB (MariaDB is a fork of MySQL) database named "Books" that contains a table named "Amazon" where I've stored information on books that includes their Amazon Standard Identification Number (ASIN). I want to be able to run a Python script to which I provide a word as a command line argument and have the script find all books in that database table that have a title containing that word and to print the title, which is stored in a column named "Description" along with the ASIN, which is stored in a column named "ASIN". To do so, I use a script with the following code:
#!/usr/bin/python
import mysql.connector, sys
def executeSQL(conn, queryTerm):
cursor = conn.cursor()
query = "select ASIN, Description from Amazon where Description like " + queryTerm
cursor.execute(query)
result = cursor.fetchall()
for row in result:
print row[0], row[1]
hostname = 'localhost'
username = 'myAcctName'
password = 'ThePassword'
database = 'Books'
try:
sys.argv[1]
except IndexError:
print "Error - missing query word! Usage ./findBook queryWord"
sys.exit(1)
else:
queryWord = "'%" + sys.argv[1] + "%'"
connection = mysql.connector.connect( host=hostname, user=username, passwd=password, db=database )
executeSQL(connection,queryWord)
connection.close()[ More Info ]
