Python-Ref > Databases and Python > Python and MySQL > Deleting data
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Deleting data

Expand/Shrink
Zdroj: (mysql6-1.py)
  1   # encoding: utf-8
  2   import MySQLdb
  3   from MySQLdb.cursors import DictCursor
  4   
  5   # connect
  6   connection = MySQLdb.connect( user="test", passwd="pass123", db="world", host="localhost", cursorclass=DictCursor)
  7   cursor1 = connection.cursor()
  8   
  9   # get all cities for czech republic
 10   cursor1.execute( "SELECT Name FROM City WHERE CountryCode='CZE';")
 11   print ", ".join( [city['Name'] for city in cursor1.fetchall()])
 12   
 13   # delete some of them (the ones which start with 'O' or with 'P')
 14   cursor1.execute( "DELETE FROM City WHERE CountryCode='CZE' AND (Name LIKE 'O%' OR Name LIKE 'P%');")
 15   print "Deleted %d cities" % (cursor1.rowcount)
 16   
 17   # check the result
 18   cursor1.execute( "SELECT Name FROM City WHERE CountryCode='CZE';")
 19   print ", ".join( [city['Name'] for city in cursor1.fetchall()])
 20   
 21   cursor1.close()
 22   
 23   connection.close()
stdout:
Praha, Brno, Ostrava, Plzen, Olomouc, Liberec, Ceské Budejovice, Hradec Králové, Ústí nad Labem, Pardubice
Deleted 5 cities
Brno, Liberec, Ceské Budejovice, Hradec Králové, Ústí nad Labem
Doba běhu: 1655.3 ms