Turinys

MySQLdb

Prisijungimas

import MySQLdb
 
db = MySQLdb.connect (host = "localhost", user="pikasphp", passwd="merakas", db="pikasphp_web")

Užklausa, rezultatai

cursor = db.cursor()
cursor.execute("SHOW TABLES")
 
result = cursor.fetchall()
 
for record in result:
	print record[0], "-->", record[1]

Kiek eilučių

# 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]

Kiek rezultatų spausdinti

# limit the resultset to 3 items
result = cursor.fetchmany(3)
 
# iterate through resultset
for record in result:
  print record[0] , "-->", record[1]

Paskutinio įrašo ID

# get ID of last inserted record
print "ID of inserted record is ", int(cursor.insert_id())

Keletas panašių užklausų

# 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.

Kiti MySQLdb klasės metodai

Nuorodos