Syntax Error when inserting data with variables in MySQLdb Python - python

I am trying to insert some data into a MySQL DB with Python and MySQLdb. When i do the following:
query = "INSERT INTO universitats (universitat) VALUES ('%s')" % (lloc)
cursor.execute(query)
db.commit()
I get this error:
Traceback (most recent call last):
File "read.py", line 39, in <module>
cursor.execute(query)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_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 'Hospitalet de Llobregat')' at line 1")
What am I doing wrong?

This lines:
query = "INSERT INTO universitats (universitat) VALUES ('%s')" % (lloc)
cursor.execute(query)
should look like this
query = "INSERT INTO universitats (universitat) VALUES (%s)"
cursor.execute(query,(lloc,))
and then commit.

Related

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.

Insert ERROR - mysql connector python 2.7

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.

Why won't this insert into my database, using python?

I am trying to insert some strings into my database.
import mysql.connector
import web
from mysql.connector import Error
import cgi, cgitb
conn = mysql.connector.connect(host='localhost', database='adatabase', user='root', password='')
cursor = conn.cursor()
if conn.is_connected():
print('Connected to MySQL database')
fullname = "fullname"
email ="email"
comments = "comments"
sql = """INSERT INTO `comments` (`id`, `name`, `email`, `comments`, `time`) VALUES (NULL, %s, %s, %s, )""" % (fullname, email, comments)
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()
It gives me this error. Note, I have mysql-connector-python_1.2.3 installed when it gave me this error.
Connected to MySQL database
Traceback (most recent call last):
File "commentsscript.cgi", line 108, in <module>
cursor.execute(sql)
File "/usr/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 494, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 683, in cmd_query
statement))
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 601, 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 ')' at line 1
and I've also gotten this error, when I didn't have mysql-connector-python installed and instead, mysqlworkbench
Traceback (most recent call last):
File "commentsscript.cgi", line 108, in <module>
cursor.execute(sql)
File "/usr/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 494, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 683, in cmd_query
statement))
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 601, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'fullname' in 'field list'
Thing's I've tried
Passing variables into a create table statement. This works.
anooog1 = "thing"
sql = """CREATE TABLE thiga (%s INT, COL2 INT )""" % (anooog1)
Also passing the strings directly. This is redundant kind of, considering that I want this to eventually pass variables from HTML. I've been testing the syntax.
sql = """INSERT INTO `comments` (`id`, `name`, `email`, `comments`, `time`) VALUES (NULL, "fullname", "email", "comments", CURRENT_TIMESTAMP)"""
(I am also having trouble getting cgi scripts to run in apache, but that's a different problem,this testing is being done on the terminal)
Don't use string formatting to insert your variables into SQL queries - this is, for the least, makes your code vulnerable to SQL injections.
You are also missing the value for the time column in your query and I'm pretty sure you had to put your placeholders into quotes (%s -> "%s").
Anyway, parameterize your query:
sql = """
INSERT INTO
comments
(id, name, email, comments, time)
VALUES
(NULL, %s, %s, %s, CURRENT_TIMESTAMP)
"""
cursor.execute(sql, (fullname, email, comments))
Note that quotes around placeholders are not needed here - the database driver in this case handles the type conversions automatically.

Running Py ODBC queries?

Trying to query for dates in an Access DB, and it keeps returning the follow error:
Traceback (most recent call last):
File "C:/Users/sniederriter/Desktop/SATG.py", line 10, in <module>
for row in cursor.execute(SQL):
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 1605, in execute
self.execdirect(query_string)
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 1631, in execdirect
check_success(self, ret)
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 986, in check_success
ctrl_err(SQL_HANDLE_STMT, ODBC_obj.stmt_h, ret, ODBC_obj.ansi)
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 954, in ctrl_err
raise ProgrammingError(state,err_text)
pypyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'Date *'.")
Here is my code:
import pypyodbc
DBfile = (r'C:\Users\sniederriter\Desktop\SATGexpenses.accdb')
conn = pypyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='+DBfile)
cursor = conn.cursor()
print(DBfile)
SQL = 'SELECT Date * FROM 20142015;'
for row in cursor.execute(SQL):
print (row.Date)
cursor.close()
conn.close()
Your MySQL query is wrong. Following code selects all fields from the table:
SELECT * FROM Table
If you want specific fields write:
SELECT field1, field2, field3 FROM table
But only do one of the things. Either all or specified fields.

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',)

Categories