How can I get the real cursor or update or reset it?

I have three py files: Client, Server and SQL

As my design, every time the Client starts, the server has to call SQL to add data to MySQL or print "It has been added".

But when I get "It has been added" and then delete data in MySQL, SQL does not add data again, it still shows "It has been added".

Like my project, every time I get data from the client, the server has to call SQL.

When I delete data in MySQL, common_ID should be False, but it is still the last number.

SQL

def main(computer_name,user_name):
     print '==========SQL start=========='
     common_ID=searchComputerName(computer_name)
     if(common_ID):
         print'01'
         if(compareUserName(common_ID,user_name)):
             print"It has been added."
         else:
             updateUserName(common_ID,user_name)
     else:
         common_ID=searchUserName(user_name)
         if(common_ID):
             updateComputerName(common_ID,computer_name)
         else:
             addNewItem(user_name,computer_name)
     print '===========SQL end==========='

def searchComputerName(computer_name):
     print'->searchComputerName'
     c = db.cursor()
     sql="SELECT * FROM `mtk_pc_name` WHERE name='%s'"%computer_name
     print sql
     a=c.execute(sql)
     print a
     if(c.execute(sql)):
         common_ID = c.fetchone()[0]
         print common_ID
         c.close()
         return common_ID
     else:
         print'searchComputerName false'
         c.close()
         return False

      

Server

def clientThread(conn):
    print'->clientThread'
    message = conn.recv(1024)
    data = message.split(' ')
    computer_name = data[0]
    user_name = data[1]
    main(computer_name,user_name)
    reply = 'OK'
    conn.sendall(reply)
    print "reply OK"
    conn.close()
    print 'clone.close'
while 1:
    conn,addr = s.accept()
    print'Connected with'+addr[0]+':'+str(addr[1])
    clientThread(conn)
    print 'End\n'

      

+3


source to share


1 answer


I find a solution.

In each function in SQL, add the following:

db = MySQLdb.connect(host=hostName,user=userName,passwd=password,db=database)

cursor=db.cursor()

      

It works fine now.



Obviously, I'll extract it as a parameter to the function. Finally, it looks like this:

def searchComputerName(computer_name,cursor):
def addNewItem(user_name,computer_name,cursor,db):

      

Though I don't understand why the global db and cursor declared first don't work well.

0


source







All Articles