import MySQLdb db = MySQLdb.connect (host = "localhost", user="pikasphp", passwd="merakas", db="pikasphp_web")
cursor = db.cursor() cursor.execute("SHOW TABLES") result = cursor.fetchall() for record in result: print record[0], "-->", record[1]
# get the number of rows in the resultset numrows = int(cursor.rowcount) # get and display one row at a time for x in range(0,numrows): row = cursor.fetchone() print row[0], "-->", row[1]
# limit the resultset to 3 items result = cursor.fetchmany(3) # iterate through resultset for record in result: print record[0] , "-->", record[1]
# get ID of last inserted record print "ID of inserted record is ", int(cursor.insert_id())
# dynamically generate SQL statements from list cursor.executemany("INSERT INTO animals (name, species) VALUES (%s, %s)", [ ('Rollo', 'Rat'), ('Dudley', 'Dolphin'), ('Mark', 'Marmoset') ])
In this case, the same query is repeated multiple times, with a different set of values each time. The values for each iteration are provided to the executemany()
method as a Python list; each element of the list is a tuple containing the values for that iteration.
connection.begin()
- start a transactionconnection.apilevel()
- returns the current DB API levelconnection.conv()
- set type conversion options between MySQL and Pythonconnection.commit()
- commit a transactionconnection.rollback()
- roll back a transaction