Creating a MySQL Database


import MySQLdb myDB = MySQLdb.connect(host="127.0.0.1", port=3306) cHandler = myDB.cursor() cHandler.execute("CREATE DATABASE schedule") cHandler.execute("CREATE TABLE Arrivals (city TEXT,\                            flight TEXT, time TEXT)")

Once you have connected to a MySQL database and got a SQL command cursor object, creating databases and tables is just a matter of sending the appropriately formatted SQL commands to the server.

To create a new database, use the execute(operation [, parameters]) function of the cursor object to initiate the CREATE DATABASE <database> SQL command. To create a new table, use the execute() function of the cursor object to initiate the CREATE Table <tablename> (<column name> <column type>, ...) SQL command.

To verify that the table has been created, use the SHOW TABLES SQL command to return a list of table entries available in the database.

Note

The table entries that are returned are in the form of a list. The first entry in the list is the table name.


To verify structure of a specific table, use the DESCRIBE <tablename> SQL command to return a list of field entries included in the table.

Note

The field entries that are returned are in the form of a list. The first entry in the list is the field name and the second is field type.


Caution

You must have appropriate permissions on the mySQL server to be able to create a database.


import MySQLdb #Connect to MySQL Server myDB = MySQLdb.connect(host="127.0.0.1", port=3306) #Get the cursor object cHandler = myDB.cursor() #Create database cHandler.execute("CREATE DATABASE schedule") #Select database cHandler.execute("USE schedule") #Create table cHandler.execute("CREATE TABLE Arrivals (city TEXT,\                   flight TEXT, time TEXT)") #Show created table cHandler.execute("SHOW TABLES") results = cHandler.fetchall() print results #Describe the table cHandler.execute("DESCRIBE Arrivals") results = cHandler.fetchall() print results myDB.close()


MySQL_create.py

(('arrivals',),) (('city', 'text', 'YES', '', None, ''), ('flight', 'text', 'YES', '', None, ''), ('time', 'text', 'YES', '', None, ''))


Output from MySQL_create.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