D&C Lug - Home Page
Devon & Cornwall Linux Users' Group

[ Date Index ][ Thread Index ]
[ <= Previous by date / thread ] [ Next by date / thread => ]

Re: [LUG] Python Question....



On Tuesday 13 May 2003 11:09, you wrote:
> I have a question relating to python...
>
> I am trying to query a MySQL database and get the result in a
> readable format for me to be able to process...

> # Connect to the MySQL database
> db=_mysql.connect(host="localhost",user="<username>",passwd="<
>password>",db="<dbname>")

The Nutshell book has jjust been published.  Seems good.

I have this lying around ...

import MySQLdb
try:
	conn = MySQLdb.connect(host="localhost", user="user", 
passwd="password")
	curs = conn.cursor()
	curs.execute("USE practice")




	curs.execute("SELECT * FROM master WHERE Patcode ='   100'")
	#print curs
	thispt = curs.fetchall()

	for item in thispt:
		print item[0],item[1],item[2] #,item[3],item[4],item[5]

	sql = ""
	sql = "SELECT * FROM rxhist WHERE patcode='"
	print sql
	print thispt[0] # + "'"
	#curs.execute(sql)
	#thisrxhist = curs.fetchall()
	#print thisrxhist
	mysql_close();
except:
	print "it didn't work properly"
	

But that may be the previous model, before the Python DB API ...

I am sure that however you get a result back, you then have to 
work through it - what you get with your 
print result 
is the handle of the result object, which is a dictionary or an 
array of dictionaries I think...

Aha,  here is a working example

import MySQLdb

#    print MySQLdb.apilevel   # is 2.0
conn=MySQLdb.connect('212.67.197.12', 'user', 'password')

#print conn
cursor=conn.cursor()
cursor.execute("SELECT * FROM exelearn.Practices")
result= cursor.fetchall()
print "There are ", cursor.rowcount , " entries"

for record in result:
    print record[0] ,record[1],record[2],record[3],record[4]


strName=raw_input("Give name of Practice exactly as in 
directory")
cursor=conn.cursor()
cursor.execute("SELECT * FROM exelearn.Practices WHERE 
PracticeName='" + strName + "'")
result= cursor.fetchall()
print "There are ", cursor.rowcount , " entries"
if cursor.rowcount == 1:
    for record in result:
        print record[0] ,record[1],record[2],record[3],record[4]

else:
    print "Error: no single unique record identified"
        # stopping there would make sense
    


-- 
From one of the Linux desktops of Dr Adrian Midgley 
http://www.defoam.net/             

--
The Mailing List for the Devon & Cornwall LUG
Mail majordomo@xxxxxxxxxxxx with "unsubscribe list" in the
message body to unsubscribe.


Lynx friendly