import socket
import json
import pymysql
HOST = ''
PORT =
i = 0
list_data =[]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while True :
try :
conn,addr = s.accept()
data = conn.recv(1024)
dic_data = json.loads(dta)
list_data.insert(i, dic_data)
i += 1
if len(list_data) == 4 :
conn.close()
pymysqlcon(list_data)
i = 0
list_data = []
except : continue
def pymysqlcon(final_list):
conn = pymysql.connect(host="", user="admin", password="", db = "gpsdb")
curs = conn.cursor()
for i in range(0, len(final_list)):
final_data = final_list[i]
sql = ("INSERT INTO gpsdata (cname, date, gtime, address) VALUES (%(cname)s, %(date)s, %(gtime)s, %(address)s)")
curs.execute(sql, final_data)
conn.commit()
conn.close()
The code is as follows: This is a vmware ubuntu environment using Python 2.7. It's an error in a sentence that runs in a loop.
After receiving data from the client after the try, change the data from json to dict and save it in the list If the size of the list is calculated using len(), and it becomes 4, it is a code to put it into db with the pimysql module I don't think the if door is working.
When the if statement is activated, the list is initialized and the size of the list becomes zero, so it goes again, but it does not become zero and there is no data value in the db.
Also, both socket communication and pimysql use the same conn, so I want to know if there is no problem if I close() after use.
socket pymysql python2.7 if문
conn,addr = s.accept()
accept should be called only once when a connection request is received from the client. You have to accept before entering the while loop, and only recv inside the while loop.
dic_data = json.loads(dta)
dta => data
This part is probably a typo, right?
Because the conn used to accept socket is a global variable, we recommend changing conn to a different name in the pimysqlcon function.
© 2024 OneMinuteCode. All rights reserved.