Reputation: 7
I'm trying to set up a python program to edit a database from input from my arduino, and the try:
command is giving me an error and I'm not sure I understand why
import serial
import MySQLdb
dbConn = MySQLdb.connect("localhost","root","Mecool100","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")
try:
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = data”)
dbConn.commit()
cursor.close()
except MySQLdb.IntegrityError:
print "Failed to insert data"
finally:
cursor.close()
except:
print "Failed to get data"
This code is returning the following error:
File "test.py", line 21
try:
^
SyntaxError: invalid syntax
Could someone please assist me in finding my error?
Thank you :)
Upvotes: 1
Views: 3029
Reputation: 2244
The others who are saying that you need except
blocks after your try
are right...but they're missing that you already have them. Really, the problem is that this line
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = data”)
should be this:
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = data")
”
is in fact not the same character as "
; it is codepoint 146 in CP1252 (sometimes incorrectly called ANSI) or codepoint 8221 in Unicode. Do chr("”")
to see for yourself.
You also need to indent the third try
block, so in the end, your code should look like this:
import serial
import MySQLdb
dbConn = MySQLdb.connect("localhost","root","Mecool100","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")
try:
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = data")
dbConn.commit()
cursor.close()
except MySQLdb.IntegrityError:
print "Failed to insert data"
finally:
cursor.close()
except:
print "Failed to get data"
Upvotes: 2
Reputation: 363183
You need an except
and/or finally
block for the second try:
block. A try
without an except
or finally
does not make sense, so the extra block is compulsory by syntax.
In your third try
block, you should move the except
ahead of the finally
.
Additionally, you have a gnarly quote character on this line:
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = data”)
Make sure it's a "
in your code, not a ”
.
Upvotes: 1
Reputation: 3218
every try statement must have an except clause
try:
1/0
except ZeroDivisionError:
print("oops")
Upvotes: 0