Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

whats the best way to go about this in python? I have a number of like so

def test1()
    .... code .....
def test2()
    .... code .....
def test3()
    .... code .....

how could I create one database connection and use it across all the functions? I'm connecting to my database in a test file like so:

import MySQLdb as mdb
import sys

try:
    con = mdb.connect('10.243.17.13', 'mark', 'LiverpoolFc', 'dex');

    cur = con.cursor()
    cur.execute("SELECT VERSION()")

    ver = cur.fetchone()

    print "Database version : %s " % ver

except mdb.Error, e:

    print "Error %d: %s" % (e.args[0],e.args[1])
    sys.exit(1)
share|improve this question
    
Are these meant to be unit-tests? When that's the case, they shouldn't use the database because that would introduce dependencies on the state of an external system. You should use mock-objects to simulate the database instead. –  Philipp Nov 6 '14 at 13:33
    
hi @Philipp no its just a theoretical programmer, just having a play with Python, learning by doing –  twigg Nov 6 '14 at 14:04

1 Answer 1

The best thing it occurs to me it's creating a class, so you can save the connection in an attribute, and then use it by all the test methods. In example:

import sys
import MySQLdb as mdb

class MyDBTest():

    def __init__(self, host, user, passw, db):
        try:
            self.con = mdb.connect(host, user, passw, db)
            self.cur = self.con.cursor()
        except mdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            sys.exit(1)

    def show_version(self):
            self.cur.execute("SELECT VERSION()")
            print "Database version : %s " % self.cur.fetchone()

    def test1(self):
        # Do something with self.con or self.cur
        pass

    def test2(self):
        # Do something with self.con or self.cur
        pass

if __name__ == '__main__':  # If it's executed like a script (not imported)
    db = MyDBTest('10.243.17.13', 'mark', 'LiverpoolFc', 'dex')
    db.show_version()
    db.test1()
    db.test2()

In the example I've put the error checking (try-except) inside the class. But you could also don't put it in there and leave the main (__name__ == __main__ part) to handle the errors if they occurr inside MyDBTest.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.