Insert ERROR - mysql connector python 2.7 - python

I am attempting to insert some sentiment analysis results (google cloud language API) into a mysql database. I am using the mysql connector.
import mysql.connector
from google.cloud import language
cnx = mysql.connector.connect(user='blahuser', password='Blahpw',
host='BlahIP',
database='FeedbackDB')
cursor = cnx.cursor(buffered=True)
CoreSQL = ("SELECT ResID, TextResp FROM Response")
cursor.execute(CoreSQL)
client = language.Client()
for row in cursor:
document = client.document_from_text(row[1])
sent_analysis = document.analyze_sentiment()
sentiment = sent_analysis.sentiment
annotations = document.annotate_text(include_sentiment=True, include_syntax=True, include_entities=True)
print(row[0], sentiment.score, sentiment.magnitude)
ResID_ =row[0]
PhraseSent_ = sentiment.score
PhraseMag_ = sentiment.magnitude
SQLInsertCmd = ("INSERT INTO PhraseAnalysis (ResID, PhraseSent, PhraseMag), VALUES (%s,%s,%s)");
cursor.execute(SQLInsertCmd, (ResID_, PhraseSent_,PhraseMag_))
cnx.commit()
cursor.close()
cnx.close()
The error I get indicates I have an issue with my INSERT statement :
python tm16.py
(1, -0.4, 2.2)
Traceback (most recent call last):
File "tm16.py", line 27, in <module>
cursor.execute(SQLInsertCmd, (ResID_, PhraseSent_,PhraseMag_))
File "/usr/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 559, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 494, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 396, in _handle_result
raise errors.get_exception(packet)
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 ' VALUES (1,-0.4,2.2)' at line 1
There are lots of INSERT examples online, but I haven't be able to resolve. New to coding- no doubt something simple. Can someone point out where I am going wrong?
Mike

You have an unnecessary comma after the end of the fields list.

Related

MYSQL Connector Python Issue | Select Query

I'm having a problem with this MySQL Query, how can I fix that?
valori = (message.from_user.id, message.from_user.username)
verifica = "SELECT * FROM utenti WHERE ID = %s, Username = %s"
cursor.execute(verifica, valori)
A sample of variable "valori":
(1062473636, 'Partizionare')
Error:
1064 (42000): 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 ' Username = 'Partizionare'' at line 1
Traceback (most recent call last):
File "/home/lello/.local/lib/python3.7/site-packages/pyrogram/dispatcher.py", line 217, in handler_worker
await handler.callback(self.client, *args)
File "/home/lello/Documents/Telegram/LelloDevBot/pyro.py", line 19, in start
cursor.execute(verifica, valori)
File "/home/lello/.local/lib/python3.7/site-packages/mysql/connector/cursor.py", line 551, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/home/lello/.local/lib/python3.7/site-packages/mysql/connector/connection.py", line 490, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/home/lello/.local/lib/python3.7/site-packages/mysql/connector/connection.py", line 395, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 ' Username = 'Partizionare'' at line 1
There's no such thing as , in conditions, you mean AND.

How to add a record to a table in MySQL using python?

In my code, I am trying to insert data into the 'user_attempts' table of my DB which has two fields: attemptID (auto-incremented) and username. Therefore when I'm passing data in I only have to pass the username as the attemptID is generated by MySQL. This my code:
username='test1'
add_userattempt=mycursor.execute('INSERT INTO user_attempt (username) VALUES %(currentuser)s', {'currentuser' :username})
mydb.commit()
However it returns this error:
Traceback (most recent call last):
File "C:\Users\User\Desktop\project\AA game things\Iteration 1\review.py", line 266, in <module>
reviewPage(screen) # the home screen function is called which essentially starts the whole program.
File "C:\Users\User\Desktop\project\AA game things\Iteration 1\review.py", line 132, in reviewPage
add_userattempt=mycursor.execute('INSERT INTO user_attempt (username) VALUES %(currentuser)s', {'currentuser' :username})
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\cursor.py", line 569, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\connection.py", line 590, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\connection.py", line 478, in _handle_result
raise errors.get_exception(packet)
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 ''test1'' at line 1
As shown by the error you get, you have a syntax error in your SQL code.
Instead of
mycursor.execute('INSERT INTO user_attempt (username) VALUES %(currentuser)s', {'currentuser' :username})
it should be
mycursor.execute('INSERT INTO user_attempt(username) VALUES(%s)', username)
This webpage here (https://www.mysqltutorial.org/python-mysql-insert/) explains the whole procedure of inserting data into MySQL tables using python pretty well.
Why do you declare your execute statement as a variable?
Hope this helps!

Python with mysql query insertion - single parameter

Below are the code that is not working
#!/usr/bin/python
import urllib
import datetime
import mysql.connector
data['price'] = 100
# Write to database
cnx = mysql.connector.connect(user='user', password='pw', database='db')
cursor = cnx.cursor()
query = ("INSERT INTO records(price) VALUES(%s) ")
cursor.execute(query, (data['price']))
cnx.commit()
cursor.close()
cnx.close()
MySQL has the corresponding table and column.
id (PRIMARY INT AUTO_INCREMENT)
price (FLOAT)
There is no connection problem.
It gives the following error. Any idea?
Traceback (most recent call last): File "./sys-fetchdata.py", line
22, in
cursor.execute(query, (data['price'])) File "/usr/lib/python2.7/dist-packages/mysql/connector/cursor.py", line
507, in execute
self._handle_result(self._connection.cmd_query(stmt)) File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line
722, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File
"/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line
640, in _handle_result
raise errors.get_exception(packet) 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 '%s)' at line 1
the MySQLCursor.execute() method takes a tuple (or a dict) as second (params) argument.
in your case: it should be (data['price'], ) (note the additional comma; without it the brackets have no effect) instead of (data['price']).
Let's try to find a solution:
Do not execute your query, instead mogrify and print it. For example:
query = ("INSERT INTO records(price) VALUES(%s) ")
query_to_be_executed = cursor.mogrify(query, (data['price']))
print(query_to_be_executed)
Next try to execute your printed query manually in bash or phpMyAdmin and fix it.
Finally use fixed query in your python code.

Mysql syntax error when inserting string using Python connector

very new to both MySQL and Python so any help would be appreciated. This syntax error is driving me crazy because I feel like I'm following the tutorials exactly...
Here's my very simple DB:
>>> cursor.execute('DESCRIBE Sports_Master')
>>> cursor.fetchall()
[(u'ID', u'int(11)', u'NO', u'PRI', None, u'auto_increment'), (u'Name', u'varchar(255)', u'NO', u'', None, u'')]
What I'm attempting to do:
import mysql.connector
conn = mysql.connector.connect(**mysql_config)
cursor = conn.cursor()
test_name = 'Test'
insert_statement = ("INSERT INTO Sports_Master (Name) "
"VALUES (%s)"
)
cursor.execute(insert_statement, test_name)
And this is the resulting error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Library/Python/2.7/site-packages/mysql/connector/cursor.py", line 507, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 722, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 640, in _handle_result
raise errors.get_exception(packet)
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 '%s)' at line 1
Is there something obvious that I'm doing wrong?
IIRC, The values that you pass in are supposed to be a non-string sequences (or mappings if you want to use the %(name) syntax). tuples work nicely for what you're doing:
test_name = ('Test',)

python DELETE rows from mysql with REGEXP and mysql connector

Code setup according to examples found here:
for ICAO_COUNTRY in ['GM','DA','DT']:
table='aerodrome'
query = 'delete from %s where code_icao regexp "%s[A-Z][A-Z]"'
cursor.execute(query,(table,ICAO_COUNTRY))
gives for answer
Traceback (most recent call last):
File "bin/cleanup2", line 22, in <module>
cursor.execute(query,(table,ICAO_COUNTRY))
File "/usr/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 491, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 635, in cmd_query statement))
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 553, in _handle_result
raise errors.get_exception(packet)
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 ''aerodrome' where code_icao regexp "'GM'[A-Z][A-Z]"' at line 1
It seems to me that the single quotes get transferred to the MySql engine, this is not what I want.
Single quotes are automatically added since you are binding a parameter that is supposed to be a field, a table name, a value. But you can't use this syntax to make a string replacement, it is different from a basic formatted string with placeholders
You can solve the problem with:
for ICAO_COUNTRY in ['GM','DA','DT']:
table='aerodrome'
query = 'delete from %s where code_icao regexp \'' + ICAO_COUNTRY + '[A-Z][A-Z]\''
cursor.execute(query, table)
Or you can change your query to
query = 'delete from %s where code_icao regexp concat(%s, \'[A-Z][A-Z]\')'
cursor.execute(query, (table,ICAO_COUNTRY))

Categories