Using list_dbs() and list_tables function of MySQLDB with python

Gerhard Häring gerhard.haering at opus-gmbh.net
Wed Jan 15 07:34:40 EST 2003


sonu <u2_sonu at yahoo.co.in> wrote:
> dear friends,
> 
> i m using list_dbs() and list_tables() function in my application but
> finding a problem in running this code successfully.
> 
> The code i m using is:
> # !/usr/bin/Python
> import MySQLdb
> hostname = "192.168.0.11"
> username = "root"

Using the root user like this is a very bad idea.

> password = ""

With an empty password even more so.

> database = "test"
> conn = MySQLdb.connect (hostname, username, password, database)
> for db in conn.list_dbs():
>     for tbl in conn.list_tables(db[0]):

You can't use SQL functions like this (using methods on the connection
object). Instead use something like:

    cursor = conn.cursor()
    cursor.execute("select list_dbs()")
    for db_row in cursor.fetchall():
        cursor.execute("select list_tables(%s)", (db_row[0],))
        for table_row in cursor.fetchall():
            # ...

Note the use of DB-API parameter binding.

> [...] Please help me in solving the problem.

You should consider reading some more about the Python DB-API. URLs of
interest are:

http://www.python.org/peps/pep-0249.html
http://www.amk.ca/python/writing/DB-API.html

Gerhard
-- 
Gerhard Häring
OPUS GmbH München
Tel.: +49 89 - 889 49 7 - 32
http://www.opus-gmbh.net/




More information about the Python-list mailing list