Difference between revisions of "Python update mysql"

From MyWiki
Jump to: navigation, search
(Created page with "<source lang="python"> #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor objec...")
 
 
Line 10: Line 10:
 
cursor = db.cursor()
 
cursor = db.cursor()
  
# Prepare SQL query to INSERT a record into the database.
+
# Prepare SQL query to UPDATE required records
sql = "SELECT * FROM EMPLOYEE \
+
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
      WHERE INCOME > '%d'" % (1000)
+
                          WHERE SEX = '%c'" % ('M')
 
try:
 
try:
 
   # Execute the SQL command
 
   # Execute the SQL command
 
   cursor.execute(sql)
 
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
+
   # Commit your changes in the database
   results = cursor.fetchall()
+
   db.commit()
  for row in results:
+
      fname = row[0]
+
      lname = row[1]
+
      age = row[2]
+
      sex = row[3]
+
      income = row[4]
+
      # Now print fetched result
+
      print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
+
            (fname, lname, age, sex, income )
+
 
except:
 
except:
   print "Error: unable to fecth data"
+
   # Rollback in case there is any error
 +
  db.rollback()
  
 
# disconnect from server
 
# disconnect from server
 
db.close()
 
db.close()
 
 
</source>
 
</source>

Latest revision as of 15:16, 25 February 2016

#!/usr/bin/python
 
import MySQLdb
 
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
 
# prepare a cursor object using cursor() method
cursor = db.cursor()
 
# Prepare SQL query to UPDATE required records
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
                          WHERE SEX = '%c'" % ('M')
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()
 
# disconnect from server
db.close()