I’m encountering a syntax error when attempting to insert data into my MySQL database using Python. As I’m quite new to programming, I might be overlooking something basic.
Here’s the code I’m working with:
import os
import MySQLdb
import datetime
connection = MySQLdb.connect(host="localhost", user="root", passwd="mypass", db="testdb")
cur = connection.cursor()
logfile = os.popen('tail -f application.log')
while True:
line = logfile.readline()
if not line:
break
parts = line.split()
if parts[2] == 'ERROR':
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cur.execute("INSERT INTO events (timestamp, type, details) values (timestamp, parts[3], parts[6])")
if parts[2] == 'SUCCESS':
print(parts[3] + '\t' + parts[6])
When I run this, I receive the following error:
Traceback (most recent call last):
File "monitor.py", line 15, in <module>
cur.execute("INSERT INTO events (timestamp, type, details) values (timestamp, parts[3], parts[6])")
File "/usr/lib/python2.7/site-packages/MySQLdb/cursors.py", line 163, in execute
self.errorhandler(self, exc, value)
ProgrammingError: (1064, "You have an error in your SQL syntax near 'parts[3], parts[6]' at line 1")
I believe that my INSERT statement might have an issue, but I’m not exactly sure what it is. The data looks like this:
ACTIVE System.Process.Started:[email protected]:14.32
Do I need to escape the values somehow before attempting to insert them? What am I missing here?