MoonPoint Support Logo

 

Shop Amazon Warehouse Deals - Deep Discounts on Open-box and Used ProductsAmazon Warehouse Deals



Advanced Search
August
Sun Mon Tue Wed Thu Fri Sat
   
26
   
2017
Months
Aug


Sat, Aug 26, 2017 9:29 pm

Querying a MariaDB or MySQL database using Python

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 ]

[/languages/python] permanent link

Valid HTML 4.01 Transitional

Privacy Policy   Contact

Blosxom logo