[Tutor] MySQL Connection Function
ajikoe at gmail.com
Tue Jun 21 20:58:25 CEST 2005
This a very simple connection using mysql.
1. connect to mysql:
db = mySQLdb.connect(user='root',passwd='something')
2. To execute and get the result:
c = db.cursor()
result = c.fetchall()
you can wrap it in a class object.
On 6/21/05, Don Parris <webdev at matheteuo.org> wrote:
> As a newbie developer, the easiest way for me to connect to MySQL is to
> just copy & paste the connection commands into each funtion I write.
> However, I know that's far from ideal, and consumes more time than its
> worth. I would like to create a MySQL connection function that I can just
> call up whenever I need it from within an other function.
> ### The Connection Definition ###
> # def mysql_Conn():
> # Create a connection object and create a cursor.
> # Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="user",
> passwd="password", db="chaddb_test") # email text wrap here
> # Cursor = Con.cursor()
> ### The function that Calls the Connection ###
> def mbr_Roster():
> # Make SQL string and execute it.
> sql = "SELECT fst_name, lst_name FROM person\
> where env_num is not null\
> order by lst_name"
> # Fetch all results from the cursor into a sequence and close the
> # connection.
> Results = Cursor.fetchall()
> How do I get mbr_Roster() to recognize the 'Cursor' from mysql_Conn()? Do I
> need to declare the cursor as a global variable?
> >From the Traceback:
> global name 'Cursor' is not defined
> evangelinux GNU Evangelist
> http://matheteuo.org/ http://chaddb.sourceforge.net/
> "Free software is like God's love - you can share it with anyone anytime
> Tutor maillist - Tutor at python.org
More information about the Tutor