Once installed the module, you can import it like any other module:
To access a database, it is best to define a class. Here I define a class called Table which allows me to retrieve data (__getitem__) and to know the number of records (__len__).
class Table: def __init__(self, db, name): self.db = db self.name = name self.dbc = self.db.cursor() def __getitem__(self, item): self.dbc.execute("select * from %s limit %s, 1" %(self.name, item)) return self.dbc.fetchone() def __len__(self): self.dbc.execute("select count(*) from %s" % (self.name)) l = int(self.dbc.fetchone()) return l
We need to define the database and create an instance of Table.
db = MySQLdb.connect( db="testable") records = Table(db, "test")
Here the database name is 'testable'. The table from 'testable' which we will query is 'test'. It may be stating the obvious, but before executing the program, you must ensure that you actually have access to a database and table by these names (or whatever names you insert into the program). As usual, one can tweak these lines so that the values are derived from the command line by using sys.argv and sys.argv, respectively.
We shall instead take the value of sys.argv as the value for the query. So, import the sys module by adding ", sys" to the line where we imported MySQLdb. If you are doing this in the Python shell, simply type:
>>> import sys
We need to define a main function in which we query the database. The main() function will include a simple loop for iterating through the rows of the table as follows:
def main(): for c in xrange(len(records)): fvalues = records[c] print fvalues if fvalues == sys.argv: print fvalues
Here we set up a for loop which runs from 1 (understood) to whatever the length of the table is. For each row, the entire row is read into 'fvalues'. If the first value in the row is equal to the string the program received from the user, the record is printed.
Perhaps the easiest Python module to use with MySQL is MySQLdb. In case you have not gone through the tutorial on reading from a MySQL database, MySQLdb is available from Sourceforge. The main documentation on this module may also be found at Sourceforge