StephenM StephenM - 7 months ago 19
SQL Question

Python and MySQL UPDATE

Everything is working as it should for the ping tool but MySQL updates are failing.

It should pull the ip address it is currently doing and update it in the MYSQL.

import MySQLdb
db = MySQLdb.connect(host="", # your host, usually localhost
user="root", # your username
passwd="**************", # your password
db="main_system") # name of the data base
cur = db.cursor()

from threading import Thread
import subprocess
from Queue import Queue

num_threads = 10
queue = Queue()

ips = ["", ""]

#wraps system ping command
def pinger(i, q):
"""Pings subnet"""
while True:
ip = q.get()
ret ="ping -i .1 -c 1 -W 50 %s" % ip,
stdout=open('/dev/null', 'w'),
if ret == 0:
cur.execute("UPDATE application_status SET status = 1 WHERE ip_address = %s")
print "%s: is alive" % ip
cur.execute("UPDATE application_status SET status = 0 WHERE ip_address = %s")
print "%s: did not respond" % ip
#Spawn thread pool
for i in range(num_threads):

worker = Thread(target=pinger, args=(i, queue))
#Place work in queue
for ip in ips:
#Wait until worker threads are done to exit

3kt 3kt

The problem may be that you need to commit the transactions, after calling cur.execute().

Hence you'll need to call db.commit() after all your transactions are executed.

Hope it'll be helpful.