I want to make a loop to be storing data from serial database. The code I have goes through the first loop but fails to execute in the next loops. Here is the code:
import serial
import MySQLdb
import time
dbConn = MySQLdb.connect("localhost","root","root","testing") or die ("could not connect to database")
cursor = dbConn.cursor()
device = '/dev/ttyACM0'
max=30
start=time.time()
while True:
try:
print "Trying...",device
arduino = serial.Serial(device, 9600)
except:
print "Failed to connect on",device
try:
data = arduino.readline()
pieces = data.split("\t")
try:
cursor.execute("INSERT INTO productCount (line,count) VALUES (%s,%s)", (pieces[0],pieces[1]))
dbConn.commit()
cursor.close()
except MySQLdb.IntegrityError:
print "failed to insert data"
#finally:
#cursor.close()
except:
print "Failed to get data from Arduino!"
time.sleep(10)
print "looping..."
remaining=max+start-time.time()
print "%s seconds remaining" % int(remaining)
if remaining<=0:
cursor.close()
break
You closed the cursor inside while loop. in try and finally.Put this in break condition of while loop
cursor.close()
Put it outside, or put this inside while loop
cursor = dbConn.cursor()
Related
Good day. I wrote an application on python that collects call logs from the Avaya PBX and writes them to the mysql database. It works well, but sometimes the PBX sends an empty string for some reason and the program fails. I attach the screen and code below. I understand that you need to wrap the function in an exception: try except, but I don’t understand how to do it. Please tell me how to do this.enter image description here
def write_db(item, *agrs):
connection = pymysql.connect(host='localhost',
user='acdr',
password='it8ejokd',
db='avaya_cdr',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
DBTBL = "cdr102019"
DBFLD = "Date_call, Time_call, `Sec_dur`, `clg_num_in_tag`, `dialed_num`, dep_called, dep_dialed"
dep_num_call = find_dep(item[3].replace(' ', ''))
name_dep_call = name_dep(dep_num_call)
dep_num_dial = find_dep(item[4].replace(' ', ''))
name_dep_dial = name_dep(dep_num_dial)
item.append(name_dep_call)
item.append(name_dep_dial)
item[1] = item[1] + "00"
try:
with connection.cursor() as cursor:
sql = "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES (%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql, (item))
connection.commit()
finally:
connection.close()
# Задаем адрес сервера
SERVER_ADDRESS = ('', 5100)
# Настраиваем сокет
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(SERVER_ADDRESS)
server_socket.listen(5)
print('server is running, please, press ctrl+c to stop')
# Слушаем запросы и пишем в db
while True:
connection, address = server_socket.accept()
data = connection.recv(1024)
if not(b'\x00\x00\x00' in data) and not(b'1370' in data):
str = data.decode("utf-8")
item=[str[0:6],str[7:11],str[12:17],str[18:33],str[34:57]]
print(item)
write_db(item)
connection.close()
You'll have to catch the exception, so we can cater for a few types, but just to be sure and get you up and running, you could do the following :)
try:
with connection.cursor() as cursor:
sql = (
"INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES "
"(%s,%s,%s,%s,%s,%s,%s)"
)
cursor.execute(
sql,
(item),
)
connection.commit()
except Exception as e:
print("Error occurred: %s"% e)
finally:
connection.close()
This should do the trick. I've used all four elements of try/except/else/finally here, with brief explanations of when they're executed.
try:
with connection.cursor() as cursor:
sql = "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES (%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql, (item))
except Exception: # If this code fails, ignore it
pass
else: # If the code inside 'try' succeeds, execute this code.
connection.commit()
finally: # Regardless of whether or not the code inside 'try' succeeds, execute this code
connection.close()
python code using nmap to scan a range of ip's and then store those ip's individually in mysql table.
how to scan when we need to scan a range of ip, e.g. 172.27.20.130-140. and store all ips in table of mysql. now a range is needed to be searched and each ip should be stored in table.
#NMAP SCANNING CODE
nmScan=nmap.PortScanner()
host=self._firstname.value # taking input from a pyforms gui input field
result=nmScan.scan(hosts=host, arguments='-sV -v -p 1-1024')
print('Host : %s (%s)' % (host, nmScan[host].hostname()))
print('State : %s' % nmScan[host].state())
for proto in nmScan[host].all_protocols():
print('----------')
print('Protocol : %s' % proto)
lport = nmScan[host][proto].keys()
#lport.sort()
for port in lport:
thisDict = nmScan[host][proto][port]
print ('port : %s\tstate : %s\tVersion:%s,v%s'% (port, nmScan[host][proto][port]['state'],thisDict['product'] ,thisDict['version']))
#INSERT into INPUT table CODE
try:
connection = mysql.connector.connect(host='localhost',
database='testdb',
user='root',
password='Pooja#123')
cursor = connection.cursor()
sql_insert_query = """ INSERT INTO input (sno,ip) VALUES (%s,%s)"""
so=cursor.lastrowid
sno=so
ip=self._firstname.value # taking input from a pyforms gui input field
insert_tuple = (sno,ip)
result = cursor.execute(sql_insert_query, insert_tuple)
print("inserted")
connection.commit()
except mysql.connector.Error as error :
connection.rollback() #rollback if any exception occured
print("Failed inserting record into input table {}".format(error))
finally:
#closing database connection.
if(connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
The ipaddress module is useful for this type of thing:
In [1]: import ipaddress
In [2]: addr = ipaddress.IPv4Address('172.27.20.130')
In [3]: print(addr)
172.27.20.130
In [4]: print(addr + 1)
172.27.20.131
We have two IR sensors interfaced with our RPi3, and we want to store the sensor data into the database.
This is the code we are trying to run.
db = MySQLdb.connect("localhost","Keerti","Keerti","test")
curs = db.cursor()
try:
print "module test"
time.sleep(2)
print "ready"
while True:
if GPIO.input(4):
print "motion detected 1"
curs.execute("INSERT INTO parktest(irname,irdata) VALUES('%f', '%f')" % (1,1))
time.sleep(1)
else:
print "no motion 1"
curs.execute("INSERT INTO parktest(irname,irdata) VALUES('%f', '%f')" % (1,0))
time.sleep(1)
if GPIO.input(14):
print "motion detected 2"
curs.execute("INSERT INTO parktest(irname, irdata) VALUES('%f','%f')" % (2,1))
time.sleep(1)
else:
print "no motion 2"
curs.execute("INSERT INTO parktest(irname, irdata) VALUES('%f','%f')" % (2,0))
time.sleep(1)
except KeyboardInterrupt:
print "quit"
GPIO.cleanup()
This, runs fine without any warnings or errors. However, it isn't storing anything in the table.
What might be the issue?
After execute(), you must use commit() to confirm all the pending changes.
Or you can use rollback() to cancel all the pendings.
Otherwise, nothing will be changed in database.
import serial
import MySQLdb
dbConn = MySQLdb.connect("localhost","root","test","ISEF_DB") or die ("Could not connect to database")
cursor = dbConn.cursor()
device = '/dev/ttyACM0'
try:
print "Trying...",device
arduino = serial.Serial(device, 250000)
except:
print "Failed to connect on",device
try:
data = arduino.readline() #read data
# pieces = data.split("\t")
print "The data is:",data
if data == 461518B1:
try:
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = '461518B1'")
dbConn.commit()
cursor.close()
print "data inserted"
except MySQLdb.IntegrityError:
print "Failed to insert data"
finally:
cursor.close()
print "done"
elif data == 46154D41:
try:
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = '46154D41'")
dbConn.commit()
cursor.close()
print "data inserted"
except MySQLdb.IntegrityError:
print "Failed to insert data"
finally:
cursor.close()
print "done"
elif data == 4615A161:
try:
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = '4615A161'")
dbConn.commit()
cursor.close()
print "data inserted"
except MySQLdb.IntegrityError:
print "Failed to insert data"
finally:
cursor.close()
print "done"
elif data == 4616A511:
try:
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = '4616A511'")
dbConn.commit()
cursor.close()
print "data inserted"
except MySQLdb.IntegrityError:
print "Failed to insert data"
finally:
cursor.close()
print "done"
elif data == 46193031:
try:
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = '46193031'")
dbConn.commit()
cursor.close()
print "data inserted"
except MySQLdb.IntegrityError:
print "Failed to insert data"
finally:
cursor.close()
print "done"
elif data == 46196771:
try:
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = '46196771'")
dbConn.commit()
cursor.close()
print "data inserted"
except MySQLdb.IntegrityError:
print "Failed to insert data"
finally:
cursor.close()
print "done"
elif data == 461A79D1:
try:
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = '461A79D1'")
dbConn.commit()
cursor.close()
print "data inserted"
except MySQLdb.IntegrityError:
print "Failed to insert data"
finally:
cursor.close()
print "done"
elif data == 46211881:
try:
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = '46211881'")
dbConn.commit()
cursor.close()
print "data inserted"
except MySQLdb.IntegrityError:
print "Failed to insert data"
finally:
cursor.close()
print "done"
elif data == 465598F1:
try:
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = '465598F1'")
dbConn.commit()
cursor.close()
print "data inserted"
except MySQLdb.IntegrityError:
print "Failed to insert data"
finally:
cursor.close()
print "done"
elif data == 9A2DCDE4:
try:
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = '9A2DCDE4'")
dbConn.commit()
cursor.close()
print "data inserted"
except MySQLdb.IntegrityError:
print "Failed to insert data"
finally:
cursor.close()
print "done"
else:
print "Card not recognized"
except:
print "Failed to get data"
This code is giving me the following error
File "test.py", line 19
if 461518B1 == data:
^
SyntaxError: invalid syntax
What I am trying to do is compare a variable to a string, however it is not working. I can't see what I'm doing wrong. The data value can only be one of the 10 if statements which contain numbers and letters. I don't see any syntax problems. Could someone please help with the error?
Thank you
While this does not directly answer your question (which was adequately addressed in the comments, viz,
461518B1 is not a string, "461518B1" or '461518B1'
(Use quotes to designate string literals)
I would point out that you can modify your code to avoid redundancy, since you appear to be using the same block of code in each of the if/elif` blocks:
id_values = ['461518B1', '46154D41', '4615A161', '4616A511', '46193031', '46196771', '461A79D1', '46211881', '465598F1', '9A2DCDE4']
data = arduino.readline() # read data
data = data.strip() # get rid of whitespace like '\r\n'
print "The data is:",data
if data in id_values:
try:
cursor.execute("UPDATE 'ISEF_DB'.'attendance' SET 'present'='1' WHERE 'id' = '" + data + "'")
dbConn.commit()
cursor.close()
print "data inserted"
except MySQLdb.IntegrityError:
print "Failed to insert data"
finally:
cursor.close()
print "done"
else:
print "Card not recognized {}".format(data)
I have a server with socket, when client connect a new thread start to record the recive data in a mysql database, the script does it fine but i have a infinite while and the script only work for 4 hours i need the server work at least for 24 hours.
What can i do?
import time
import MySQLdb
import sys
from socket import *
myHost = ''
myPort = 6250
sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.bind((myHost, myPort))
sockobj.listen(10)
print 'Server On'
def handleClient(connection):
time.sleep(0.1)
while True:
try:
data = connection.recv(256)
except timeout:
break
if not data:
break
if 'q' not in data:
if ',' in data:
dato = data.split(',')
try:
db=MySQLdb.connect(host='localhost',user='',passwd='',db='')
cursor=db.cursor()
sql = "INSERT INTO imei"+dato[1]+" (imei, estado, fecha, numero) VALUES ('%s','%s','%s','%s')"%(dato[0],dato[1],dato[2],dato[3])
cursor.execute(sql)
db.close()
except MySQLdb.Error:
db.close()
break
try:
connection.send('LOAD')
except:
break
connection.close( )
thread.exit()
def dispatcher( ):
while True:
connection, address = sockobj.accept( )
try:
thread.start_new(handleClient, (connection,))
except:
dispatcher( )
dispatcher( )
if i do the same script with fork it works for 4 hours too.
I suggest you to use https://pypi.python.org/pypi/supervisor to make sure that it is running 24 hours.
Also, could you please copy-paste the traceback after this script crashes?