Adding Entries to a MySQL Database


import MySQLdb myDB = MySQLdb.connect(host="127.0.0.1", port=3306, db="schedule") cHandler = myDB.cursor() sqlCommand = "INSERT INTO Arrivals \    VALUES('%s', '%s', '%s')" % \    (city, flights[x], times[x]) cHandler.execute(sqlCommand) myDB.commit()

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

First, connect to the server using the MySQLdb modules connect function, and then use the MySQL database object to get a cursor object. In the sample code, entries are added one at a time by executing the INSERT INTO <tablename> VALUES (<data value>) SQL command using the execute function of the cursor object.

Note

Remember to use the commit() function of the cursor object to flush pending requests to the SQL database so that the changes will be written to disk.


import MySQLdb cities = ["Dallas", "Los Angeles", "New York"] flights = ["1144", "1045", "1520"] times = ["230pm", "320pm", "420pm"] #Connect to database myDB = MySQLdb.connect(host="127.0.0.1", port=3306, db="schedule") #Get cursor object cHandler = myDB.cursor() #Add entries to database x = 0 for city in cities:     sqlCommand = "INSERT INTO Arrivals \     VALUES('%s', '%s', '%s')" % \     (city, flights[x], times[x])     cHandler.execute(sqlCommand)     x += 1 #View added entries sqlCommand = "SELECT cities, flights, times FROM Arrivals" cHandler.execute(sqlCommand) results = cHandler.fetchall() print results #Commit changes to database myDB.commit() myDB.close()


MySQL_add.py

(('Dallas', '1144', '230pm'), ('Los Angeles', '1045', '320pm'), ('New York', '1520', '420pm'))


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