[DB-SIG] Simple db access
Andy Dustman
andy@dustman.net
Fri, 29 Jun 2001 16:30:51 -0400 (EDT)
On Fri, 29 Jun 2001, Piotr Trawinski wrote:
> I am pretty much new to python. At the moment i am trying to figure out
> how to make a simple connection to a mysql db. The Python Database API
> Specification doesnt make it clear for me. Could you please give me an
> example or an equilvalent of this php code:
>
> mysql_pconnect ($host,$user,$passwd);
> mysql_select_db($name,);
>
>
> $query=mysql_query("select * from test");
>
> while ($data=mysql_fetch_row($query)) {
> echo $data[0];
> echo $data[1];
> }
Example will be for MySQLdb, but is generally applicable to other DB API
modules.
import MySQLdb
db=MySQLdb.connect(host=host, user=user, passwd=passwd, db=name)
# This could also be done instead of supplying db above but is
# non-standard
# db.select_db(name)
c=db.cursor()
c.execute("select * from test")
for row in c.fetchall(): # assumes result set is not huge
print row[0], row[1]
# alternate for potentially huge result sets
# you would probably also use this non-standard connection:
# db=MySQLdb.connect(cursorclass=MySQLdb.SSCursor,...)
row = c.fetchone()
while row:
print row[0], row[1]
row = c.fetchone()
--
Andy Dustman PGP: 0xC72F3F1D
@ .net http://dustman.net/andy
I'll give spammers one bite of the apple, but they'll
have to guess which bite has the razor blade in it.