Difference between revisions of "Python update mysql"
From MyWiki
(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 | + | # Prepare SQL query to UPDATE required records |
− | sql = " | + | sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 |
− | + | WHERE SEX = '%c'" % ('M') | |
try: | try: | ||
# Execute the SQL command | # Execute the SQL command | ||
cursor.execute(sql) | cursor.execute(sql) | ||
− | # | + | # Commit your changes in the database |
− | + | db.commit() | |
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
− | + | ||
except: | except: | ||
− | + | # 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()