Python和MySQL UPDATE

时间:2016-06-16 06:06:09

标签: python mysql mysql-python

对于ping工具,一切正常,但MySQL更新失败。

它应该提取当前正在执行的IP地址并在MYSQL中更新它。

import MySQLdb
db = MySQLdb.connect(host="10.1.1.151",    # 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 = ["10.1.1.151", "10.1.1.152"]

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

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

2 个答案:

答案 0 :(得分:1)

您错过了数据(ip)与光标的绑定:

if ret == 0:
    cur.execute("UPDATE application_status SET status = 1 WHERE ip_address = %s", (ip,))                
    print "%s: is alive" % ip
else:
    cur.execute("UPDATE application_status SET status = 0 WHERE ip_address = %s", (ip,))
    print "%s: did not respond" % ip

答案 1 :(得分:0)

问题可能是您在调用cur.execute()后需要commit这些交易。

因此,您需要在执行所有交易后调用db.commit()

希望它会有所帮助。