My output works in csv, but not when trying to insert it into mysql. I get the following error and have not been able to figure it out. I'm a novice so I may be missing something obvious. Same error in Python 2x and 3x.
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key, title, content, start_date, end_date, initial_update) VALUES('reddit', 'h' at line 1")
mainDB_cnx = pymysql.connect(user='XXXX', password='XXXX',
host='XXXX',
database='Test', use_unicode=True, charset="utf8mb4")
with mainDB_cnx:
mainDB_cursor = mainDB_cnx.cursor()
mainDB_cursor.execute(
"INSERT INTO reddit(site, site_url, key, title, content, start_date, end_date, initial_update) VALUES(%s, %s, %s, %s, %s, STR_TO_DATE(%s,'%%Y-%%m-%%d'), STR_TO_DATE(%s,'%%Y-%%m-%%d'), STR_TO_DATE(%s,'%%Y-%%m-%%d'))",
(["reddit", "http://www.reddit.com", url, title, content, datetime.strptime(date,'%d %B %Y').strftime('%Y-%m-%d'), datetime.strptime('2018-07-25','%Y-%m-%d').strftime('%Y-%m-%d'), datetime.strptime('2018-07-25','%Y-%m-%d').strftime('%Y-%m-%d')]))
print("Successful")
KEY is a reserved word in the MySQL dialect of structured query language. See this. https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-8-0-detailed-K
So you must wrap that column name in delimiters whenever you mention it.
Try
INSERT INTO reddit (side, site_url, `key`, title, ....
Or, better, don't use reserved words for the names of columns in your tables. The next programmer to work on your system will thank you.
Related
I have an issue trying to upload files from Python to my database. I can insert the binary data into the table just fine using %s, but when I try to update the record, I am unable to get this to work. Am I doing something wrong?
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01\x90\x00\x00\x00\xc8\x08\x06\x00\' at line 8
Now, I know this is because the bytestring contains a ' so this doesn't work, it excepts, and leaves some security holes open if it were to work:
dbc.execute(f"""UPDATE userdata SET
emailaddr ='{email}',
firstname ='{namee}',
lastname ='{laste}',
username ='{usere}',
password ='{passe}',
phonenum ='{phone}',
photoimg ='{u_pho}'
WHERE user_id = '{user_ident}';""")
but I'm wondering if I can update a value like this:
insertcommand = f"""UPDATE userdata SET (emailaddr,firstname,lastname,username,password,phonenum,photoimg) VALUES (%s, %s, %s, %s, %s, %s, %s) WHERE user_id = '{user_ident}'"""
insertrecord = email,namee,laste,usere,passe,phone,u_pho
dbc.execute(insertcommand,insertrecord)
How would I go about updating bytestrings in MySQL with Python?
I have a syntax error in my python which which stops MySQLdb from inserting into my database. The SQL insert is below.
cursor.execute("INSERT INTO %s (description, url) VALUES (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))
I get the following error in my stack trace.
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your
SQL syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near ''four' (description, url) VALUES ('', 'http://imgur.com/a/V8sdH')' at line 1")
I would really appreciate assistance as I cannot figure this out.
EDIT:
Fixed it with the following line:
cursor.execute("INSERT INTO " + table_name + " (description, url) VALUES (%s, %s);", (key.encode("utf-8"), data[key].encode("utf-8")))
Not the most sophisticated, but I hope to use it as a jumping off point.
It looks like this is your SQL statement:
cursor.execute("INSERT INTO %s (description, url) VALUES (%s, %s);", (table_name.encode("utf-8"), key.encode("utf-8"), data[key].encode("utf-8")))
IIRC, the name of the table is not able to be parameterized (because it gets quoted improperly). You'll need to inject that into the string some other way (preferably safely -- by checking that the table name requested matches a whitelisted set of table names)... e.g.:
_TABLE_NAME_WHITELIST = frozenset(['four'])
...
if table_name not in _TABLE_NAME_WHITELIST:
raise Exception('Probably better to define a specific exception for this...')
cursor.execute("INSERT INTO {table_name} (description, url) VALUES (%s, %s);".format(table_name=table_name),
(table_name.encode("utf-8"),
key.encode("utf-8"),
data[key].encode("utf-8")))
I am trying to insert two columns of data into a MySQL table from Python. And my Insert statement is true, I guess. But I am still getting 1064 error code.
This is for MySQL server version 8.0.12 and Python 3.7. I had tried changing different methods of inserting dynamic variables.
#alter is the data value read from serial port
sql="select * from stds"
cur.execute(sql)
records=cur.fetchall()
if cur.rowcount>0:
print('Number of rows - ',cur.rowcount)
else:
print('No data in table')
for row in records:
print(row)
if row[1]==alter:
print("Student exists : ",row[1])
date = datetime.datetime.now()
print(type(date))
ins = (alter, date)
sql = "Insert into 'attendance' ('stdid', 'dt') VALUES (%s,%s)"
cur.execute(sql, ins)
cnn.commit()
print('Sucessfully Stored the Record')
#success(alter)
break
else:
print("Student doesn't exist")
I am getting this error message
Error:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''attendance' ('stdid', 'dt') VALUES ('FE0070E83D5B','2019-08-01 09:09:06.162304'' at line 1
And I am expecting that these read tag values are inserted successfully​.
Identifiers (e.g. column and table names) in MySQL (and most other flavors of SQL as well) do not take single quotes. They take either no quotes, double quotes, or maybe backticks in the case of MySQL. Try this version:
sql = "INSERT INTO attendance (stdid, dt) VALUES (%s, %s)"
ins = (alter, date)
cur.execute(sql, ins)
cnn.commit()
I am trying to execute an sql statement that should add some data to a database like so:
cursor.execute("INSERT INTO Actors (imdbPageId, fullName) VALUES (%s, %s)" % ( db.escape_string(self.imdbID), self.name))
I have also tried:
cursor.execute("INSERT INTO Actors (imdbPageId, fullName) VALUES (%s, %s)" % ( self.imdbID, self.name))
But i keep getting this error regardless of using the escape_string or not. See below:
MySQLdb._exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/name/nm0991810, Mahershala Ali)' at line 1")
I am pretty sure it has to do with the forward slash but i cant get it to work. How do i fix this issue?
If any more information is needed let me know!
Do this instead:
query = "INSERT INTO Actors (imdbPageId, fullName) VALUES (%s, %s)"
cursor.execute(query, (self.imdbID, self.name))
If I am not mistaken mysqldb takes care of this for you.
Otherwise you can do:
cursor.execute(query, (db.escape_string(self.imdbID), self.name))
I have the following sample Python code, and when I try to execute, am getting mysql error message. Context, am trying to create custom logs, log the messages, insert to a MySql table for analysis. Providing relevant portions for mysql execute.
levelnum= str(record.levelno) # 40
levelname=str(record.levelname) # ERROR
msg=str(self.log_msg) # "This error occurred: This is test message"
createtime=str(tm) #2018-06-26 03:43:47
record.name = 'MY_LOGGER'
sql = 'INSERT INTO emp.log (log_level, log_levelname, log, created_at, created_by) VALUES ('+levelnum+ ', '+levelname+ ', '+msg+ ', '+createtime+ ', '+record.name+')'
Error message: ProgrammingError: (1064, u"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'error msg, 2018-06-26 03:43:47, MY_LOGGER)' at line 1")
Am using mysql, and trying to insert to the table as follows:
try:
self.sql_cursor.execute(sql)
self.sql_conn.commit()
except pymysql.InternalError as e:
print e
print 'CRITICAL DB ERROR! Logging to database not possible!'
I think, am missing some formatting while passing parameters in the SQL query, but couldn't get the correct one.
Appreciate if someone can help fix this.
You are not quoting the timestamp, hence the error.
Rather than trying to quote the values manually, use the built-in quoting functionality provided by pymysql as part of the DBI interface.
sql = 'INSERT INTO `emp.log` (`log_level`, `log_levelname`, `log`, `created_at`, `created_by`) VALUES (%s, %s, %s, %s, %s)'
self.cursor.execute(sql, (levelnum, levelname, msg, createtime, record.name))