help with my first use of a class

wittempj@hotmail.com martin.witte at gmail.com
Fri Oct 20 02:34:48 EDT 2006


BartlebyScrivener wrote:
> I am a mere hobbyist. Spent several hours trying to make a class,
> because I think this is an occasion where I need one. But I can't make
> it work.
>
> This code "works" (only because of the global c, which I know I'm
> supposed to avoid, by using a Class). I edited the rest to leave out
> the irrelevant formatting and printing of the quotations.
>
> I've read about Classes several times, but I don't "get" them yet.
> Obviously. If I can solve one real life problem like this, then maybe
> I'll see the light.
>
> If I understand the power of Classes correctly, I could make one that
> would allow me to make a new instance that would connect to, say, an
> SQLite3 db instead of the Access db, as well as to create more methods
> that will do different SQL searches.
>
> Thank you for any help,
>
> rd
>
> --------------------------------------
>
> import mx.ODBC.Windows as odbc
> import sys
> import random
>
> def connect():
>     global c

This means you want to use a global variable c which doesn't exist yet,
an example would be to save this code to a file:

#!/usr/bin/env python

c = 0
def test_global():
    global c
    c = 1

print c

this will print 0 when you run it

>     db='DSN=Quotations'
>     conn = odbc.DriverConnect(db)
>     c = conn.cursor()
>
> def random_quote():
>     """
>     Counts all of the quotes in MS Access database Quotations2005.mdb.
>     Picks one quote at random and displays it using textwrap.
>     """
>     c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuery")
>     # Yields the number of rows with something in the quote field
>     total_quotes = c.fetchone()
>     # Get a random number somewhere between 1 and the number of total
> quotes
>     quote_number = (random.randint(1, total_quotes[0]),)
>     # Select a quote where the ID matches that number
>     c.execute ("SELECT Author, Quote FROM PythonQuoteQuery WHERE ID=?",
> quote_number)
>     quote = c.fetchone()
>     blah blah blah
>
> def print_quote()
>     code to format and print the quote (which will also have to be
> global, unless I learn Classes!)
>
>

A class structure could look like - please bear in mind that I don't
know mx.ODBC.Windows - I guess it is not completely DB-API compliant,
as you don't use a connect method.

class SQLQuery(object):
    """Object which connects to the database and can execurte SQL
commands
    """
    def __init__(self, conn):
        """conn is a dictionary {'serverId': XX, 'userId': YY,
'passWord': ZZ}
        """
        self.connection = connect(conn['userId'], conn['passWord'],
conn['serverId'])
        self.cursor = self.__connection.cursor()

    def select(self, selectqry):
    """argument selectqry specifies a sql which returns data, like a
select
    """
    self.cursor.execute(selectqry)
    return self.cursor.fetchall()

sql = SQLQuery('serverId': 'XX', 'userId': 'YY', 'passWord': 'ZZ')
qoutes = sql.select("SELECT COUNT(Quote) FROM PythonQuoteQuery")
print quotes

> if __name__ == '__main__':
>     if len(sys.argv) == 1:

sys.argv is a list, where the first argument is the name of the running
script, the second element is the first argument, etc.

>         connect()
>         random_quote()
>         print_quote()




More information about the Python-list mailing list