[Tutor] MySQL

Rick Pasotto rick@niof.net
Wed, 17 Oct 2001 21:28:54 -0400


On Wed, Oct 17, 2001 at 03:44:11PM -0500, Szilard Bokros wrote:
> Hello,
> I would like to write a python script that reads two strings from a
> MySQL table,
> creates a directory with the second name, copies in a file,
> overwrites the first  name in the database with the second name.
> My script looks like this:
> 
> As a first step it would be eenough if I could just manipulate the
> database.
> Open it, get something fromit, overwrite something in it, etc...
> right now I reduced the script to a minimal version that does not work,
> somewhere here must be an error:
> 
> #!/usr/local/python
> import MySQLdb
> db = MySQL.connect('localhost', 'eval', 'abrakadabra', 'Rumit')
> #sofar it seems to be OK
> result= db.query("""SELECT * FROM MyTableName""")
> 
> which gives back an error message.
> So I have to do something before or after the result = ... line,
> or should I import something else?
> According to the O'Reilly MySQL book there is no need to set any cursor
> to execute querys.

I think you are using an old book which references an older module that
worked differently. Note that you have imported MySQLdb and not MySQL.

This should work:

import MySQLdb
db = MyQSLdb.Connect(host='localhost', db='dbname',
                     user='user', password='passwd')
cursor = db.cursor()
try:
    cursor.execute("""select * from tablename""")
except SyntaxError,msg:
    raise "Problem!","Query description" + str(msg)
if cursor.rowcount > 0:
    rows = cursor.fetchall()
    for row in rows:
        print row[0],row[1],row[2],....
else:
    print "no rows selected"

-- 
You contend that I am wrong to teach my son science and
philosophy; I believe you are wrong to teach yours Greek and
Latin. Let us both follow the dictate of our conscience. Let us
allow the law of responsibility to operate for our families. It
will punish the one who is wrong. Let us not call in human law; it
could well punish the one who is not wrong.
	-- Frédéric Bastiat (1801-1850)
    Rick Pasotto    rickp@telocity.com    http://www.niof.net