Connecting to a MySQL Database Server


import MySQLdb myDB = MySQLdb.connect(host="127.0.0.1", /          port=3306) cHandler = myDB.cursor()

The MySQLdb module provides the standard Python DB-API 2.0 specification connect([host= [, port= [, user= [, passwd= [, db= [ , ...]]]]]]) function to connect to MySQL database servers. All the parameters to the connect function are optional. The most common parameters used are the host, port, user, passwd, and db.

Once you have successfully connected to the MySQL server, you need to get a cursor handle to send SQL requests to the server. The cursor() function returns a cursor object that can be used to execute SQL commands on the server and obtain the results.

To execute a SQL command on the server, use the execute(operation [, parameters]) function of the cursor object, where operation is basically any properly formatted SQL command string.

To retrieve the results from executing the command, use the fetchall() function of the cursor object. The fetchall function returns the results of the SQL request in a series of one or more lists depending on the data being returned.

Once you have the cursor object and are able to execute SQL commands, you can use the SHOW DATABASES SQL command to get a list of databases available on the server. To switch to a specific database, use the USE <database> SQL command.

Note

To find out which database is currently active, use the SELECT DATABASE() command to return the current database name.


import MySQLdb #Connect to MySQL Server myDB = MySQLdb.connect(host="127.0.0.1", \                        port=3306) cHandler = myDB.cursor() #Display available databases cHandler.execute("SHOW DATABASES") results = cHandler.fetchall() print"Databases\n=====================" for item in results:     print item[0] #Display current database cHandler.execute("SELECT DATABASE()") results = cHandler.fetchall() print "\nCurrent Database\n=======================" for item in results:     print item[0] #Select database cHandler.execute("USE schedule") #Display current database cHandler.execute("SELECT DATABASE()") results = cHandler.fetchall() print "\nCurrent Database\n=======================" for item in results:     print item[0] myDB.close()


MySQL_conn.py

Databases ===================== information_schema airport mysql schedule test testy Current Database ======================= None Current Database ======================= schedule


Output from MySQL_conn.py code



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net