[Tutor] MySQL Connection Function
Pujo Aji
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()
c.execute(sql comment)
result = c.fetchall()
you can wrap it in a class object.
pujo
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():
> mysql_Conn()
>
> # Make SQL string and execute it.
> sql = "SELECT fst_name, lst_name FROM person\
> where env_num is not null\
> order by lst_name"
> Cursor.execute(sql)
>
> # Fetch all results from the cursor into a sequence and close the
> # connection.
> Results = Cursor.fetchall()
> Con.close()
>
> 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
>
>
> Don
> --
> evangelinux GNU Evangelist
> http://matheteuo.org/ http://chaddb.sourceforge.net/
> "Free software is like God's love - you can share it with anyone anytime
> anywhere."
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list