[Tutor] Python & MySQL... Define port.

wormwood_3 wormwood_3 at yahoo.com
Thu Feb 12 05:57:52 CET 2009


You can specify the port of the instance you want to connect to simply by passing "port=NUM" in MySQLdb.connect(). Here is a formulation I have found generally useful:

import MySQLdb

def run_mysql(query, db, user, passwd, port=3306, socket="/var/run/mysqld/mysqld.sock", host="localhost"):
    """Runs query passed with connection info passed, returns results."""
        db = MySQLdb.connect(user=user, passwd=passwd, db=db, port=port, unix_socket=socket, host=host)
    except MySQLdb.Error, e:
        raise e
    cursor = db.cursor()
    data = cursor.fetchall()
    return data

This sets common defaults, but you can of course pass in whatever you want when you call it. 

You might also want to check out the MySQLdb docs: http://mysql-python.sourceforge.net/MySQLdb.html. It contains a number of examples.

Samuel Huckins

Homepage - http://samuelhuckins.com
Tech blog - http://dancingpenguinsoflight.com/
Photos - http://www.flickr.com/photos/samuelhuckins/
AIM - samushack | Gtalk - samushack | Skype - shuckins

From: Network Administrator <administrador.de.red at gmail.com>
To: tutor at python.org
Sent: Monday, February 9, 2009 1:29:21 PM
Subject: [Tutor] Python & MySQL... Define port.

Hello everybody!

I want to use Python to query a given MySQL database. However, this database is running on port 3308, instead the traditional 3306.

I read that (example):

MySQLdb.connect(host="dbserv', db='inv', user='smith')

can be used to query a given database; however, it didn't work in my particular case. This is my code:

connection = MySQLdb.connect (db = "netlogin", user="netadmin", pass = "r4nas", port="3308")

I appreciate if you give me assistance in the proper sintax of the last mentioned instruction.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090211/837cc3a2/attachment.htm>

More information about the Tutor mailing list