Getting started with mysqldb

Geoffrey L. Wright geoff.nospam at
Sun Sep 17 01:32:08 CEST 2000

On Sat, 16 Sep 2000 10:51:32 -0400 (EDT), Michal Wallace
<sabren at> wrote:

>Well, assuming row/currentRow was a result of a cursor.fetchone()
>call, row is not a string, but a tuple (like a list, but it can't be

Just discoved the magic of type() in Greg Wallace's post and found
that out.  DOH!

>You're getting the problem, because, as you said, currentRow
>isn't a string... but you can make it a string by doing this:
>>>> str(row)
>"(1, 'squid')

Wowzers!  That's handy.  I looked far and wide for a way to do that.
I think my python research skills need improvement.

I was about to do something really horrible -- like this:

for row in sel_radgroupreply:
	string = ""
	for item in row:
		if type(item) == type(0):
			string = "%s %i," % (string, item)
		if type(item) == type(''):
			string = "%s '%s'," % (string, item)

...where I would then form the insert statement from my string.

>Here's how I'd re-write your code:
>cur = yourMySQLConnection.cursor()
>sql = "SELECT id, GroupName, Attribute, Value from first_table"
>for row in cur.fetchall():
>    sql = """
>        INSERT INTO test_radgroupreply 
>               (id, GroupName, Attribute, Value)
>        VALUES %s
>        """ % str(row)
>    cur.execute(sql)

Well -- that both much more readable and much faster.  The python way
of inserting variable into strings like so:

	borogovesState = "mimsy"
	string = "All %s were the borogoves" % borogovesState

...stuck me as odd at first.  But I think that it actually makes for a
very readable way of doing things.  It'll certainly help to keep the
SQL contained in my python code nicely formatted.

>I tend to use "sql", "dbc", "cur", and "row" almost exclusively when
>dealing with databases because it seems to keep the code cleaner.  I
>always assign sql on a seperate line (or lines) in case I need to
>print it out to make sure I've built it correctly, or in case I need
>to change it later. Your mileage may vary.. :)

Good to know.

Well, many thanks for the help.  The friendly reputation of Pythoneers
is certainly well deserved.  :)

>- Michal


More information about the Python-list mailing list