Python 2.7.3 if compare a variable to a string - python

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)

Related

How to add exception to python function?

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()

How to do Exception handling for mysql connection in python

I'm new to python , I want to know how to do exception handling in python in a proper way.I want to raise an exception for failure of db connection.I also don't want to include all the lines of code in try block.I want to raise connection failure exception.How to do this?
try:
conn = MySQLdb.connect(host="mysql", user="root", passwd="password"
, db="database")
mycursor = conn.cursor()
query = "INSERT INTO table1(col1,col2,col3)VALUES(%s,%s,%s)"
val = (x,y,z)
mycursor.execute(query, val)
conn.commit()
conn.close()
print("Data inserted to db")
except Exception as ex:
print(ex)
conn = MySQLdb.connect(host="mysql", user="root", passwd="password"
, db="database")
mycursor = conn.cursor()
query = "INSERT INTO table1(col1,col2,col3)VALUES(%s,%s,%s)"
try:
mycursor.execute(query, val)
except MySQLdb.Error, e:
try:
print "MySQL Error [%d]: %s" % (e.args[0], e.args[1])
return None
except IndexError:
print "MySQL Error: %s" % str(e)
return None
except TypeError, e:
print(e)
return None
except ValueError, e:
print(e)
return None
finally:
mycursor.close()
conn.close()
Something like:
connected = False
try:
conn = MySQLdb.connect(host="mysql", user="root", passwd="password"
, db="database")
connected = True
except MySQLError as ex:
print(ex)
if connected:
mycursor = conn.cursor()
query = "INSERT INTO table1(col1,col2,col3)VALUES(%s,%s,%s)"
val = (x,y,z)
mycursor.execute(query, val)
conn.commit()
conn.close()
print("Data inserted to db")

Python mysql-connector commit not working

So I've been at it for hours, and there is something really weird going on.
I am looping through code to check if a table value has changed. And if so run some code.
When i run the following program everything works totally fine! The 'lock state' goes from Open to Closed as it should be doing.
import time
import mysql.connector
host = '...'
database = '...'
user = '...'
password = '...'
conn = mysql.connector.connect(host=host, database=database, user=user, password=password)
conn.start_transaction(isolation_level='READ COMMITTED')
state = 'Open'
def get_web_lock_request():
try:
cursor = conn.cursor()
cursor.execute("SELECT * FROM `doorlock`.`state`")
state = ''.join(cursor.fetchone())
cursor.close()
return state
except mysql.connector.Error as e:
print 'get_lock_state ' + format(e)
return ''
def set_web_lock_request():
try:
cursor = conn.cursor()
cursor.execute("UPDATE `doorlock`.`state` SET `state`='" + state + "'")
conn.commit()
cursor.close()
except mysql.connector.Error as e:
print 'set_lock_state: ' + format(e)
while 1:
dbstate = get_web_lock_request()
set_web_lock_request()
if state == 'Open':
state = 'Closed'
else:
state = 'Open'
time.sleep(2)
print dbstate
But in my main code this 'listening for a change' is in a thread. And for some reason the UPDATE statement does not work! even with the conn.commit()
import mysql.connector
conn = mysql.connector.connect(host=host, database=database, user=user, password=password)
conn.start_transaction(isolation_level='READ COMMITTED')
def get_web_lock_request():
try:
cursor = conn.cursor()
cursor.execute("SELECT * FROM `doorlock`.`state`")
state = ''.join(cursor.fetchone())
cursor.close()
return state
except mysql.connector.Error as e:
print 'get_lock_state ' + format(e)
return ''
def set_web_lock_request(state):
try:
cursor = conn.cursor()
cursor.execute("UPDATE `doorlock`.`state` SET `state`='" + state + "'")
conn.commit()
cursor.close()
except mysql.connector.Error as e:
print 'set_lock_state: ' + format(e)
def web_request_listener():
global updating
try:
while 1:
print 'get_web_lock_request : ' + get_web_lock_request()
print 'current_state : ' + current_state()
if get_web_lock_request() != current_state() and not updating:
if get_web_lock_request() == 'Open':
open_lock()
print 'DoorLock: State is now open'
elif get_web_lock_request() == 'Closed':
close_lock()
print 'DoorLock: State is now closed'
time.sleep(1)
except KeyboardInterrupt:
exit()
if __name__=='__main__':
try:
button_listener_thread = threading.Thread(target=button_listener)
web_request_listener_thread = threading.Thread(target=web_request_listener)
except KeyboardInterrupt:
exit()
I could really use some help, I have literallyhave nothing else to try :)
Floris

ProgrammingError: (2014, "Commands out of sync; you can't run this command now")

I am trying to make two calls to the database, calls are being multithreaded. However sometimes the first call data may be empty, and therefore it gets an error: ProgrammingError: (2014, “Commands out of sync; you can't run this command now”)
when I call the second query. Is there a way to clear the cursor without closing the database connection?
# CHECK IF NO RECORD IN DATABASE OF SKU
try:
cursor.execute('SELECT * FROM `amazon` inner join `ebay` on amazon.ASIN=ebay.SKU WHERE `ASIN` = "%s"' % (sku))
data = cursor.fetchall()
except Exception as ee:
conn.rollback()
data = None
print "Ebay error", ee
# IF NO RECORD ADD EVERYTHING
if not data:
try:
print "Inserting into ebay table: " + str((sku, float(price), int(quantity), itemID, float(cp_price)))
cursor.execute('INSERT INTO ebay VALUES ("%s", %.2f, %.2f, %s, %.2f, %s)' % (sku, float(price), int(quantity), itemID, float(cp_price), True))
conn.commit()
except Exception as ee:
print('DB insert error', ee)
i += 1
continue

Loop to read data from a serial to a database

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()

Categories

Resources