[DB-SIG] Beginner getting out...

Andy Todd andy47@halfcooked.com
Thu, 21 Mar 2002 10:32:49 +1100


Turcotte, Paul wrote:
>>Just give my an example (a simple one) of how to connect with MySQL and
> 
> add 
> 
>>something to a table. That would do. Once I get the idea I'll see how to 
>>retrieve, modify, etc.
> 
> 
> 
> This FAQ may help you get started.
> 
> http://dustman.net/andy/python/MySQLdb_obsolete/faq/MySQLdb-FAQ-3.html
> 
>>From FAQ:
> 
> <snip>
> 
> Okay, it goes something like this:
> 
>    1. Import MySQLdb.
>    2. Create a Connection object.
>    3. Create a Cursor object.
>    4. Execute your query on the Cursor object.
>    5. If your query returns rows, you can use the Cursor object to fetch
> them.
>    6. Rinse, lather, repeat.
> 
> Example:
> 
> import MySQLdb
> db = MySQLdb.connect(db='mydb',user='myuser',passwd='mypasswd')
> c = db.cursor()
> c.execute(myquery)
> results = c.fetchall()
> 
> </snip>
> 
> Suerte,
> PT
> 

And don't forget that 'myquery' in the above example must contain a 
valid SQL statement.

e.g, with a vanilla MySQL installation on Windows;

 >>> import MySQLdb
 >>> db = MySQLDb.connect(db='mysql')
 >>> c = db.cursor()
 >>> myquery = "SELECT * FROM user"
 >>> c.execute(myquery)
5L
 >>> results = c.fetchall()
 >>> results
(('localhost', 'root', '', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', ...

And it is always good practice to close a cursor when you are done with it;

 >>> c.close()

Regards,
Andy
-- 
----------------------------------------------------------------------
 From the desk of Andrew J Todd esq - http://www.halfcooked.com