I want to query MySQL tables using python program but I got this error:
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 ''10' OFFSET '0'' at line 1
The confusing thing is that when I don't use variables, the query runs perfectly as it is shown below:
cur = connection.cursor()
query = "SELECT * FROM DB.Table LIMIT 10 OFFSET 0"
cur.execute(query)
records = cur.fetchall()
for record in records:
print(record)
But I need to select data batch by batch and I have to do the above command in a for loop. And I need to define variables. But I got error 1064. Here is the code with error:
i = 0
p = str(i)
j = 10
q = str(j)
cur = connection.cursor()
query = "SELECT * FROM DB.Table LIMIT %s OFFSET %s"
cur.execute(query,(q,p,))
records = cur.fetchall()
for record in records:
print(record)
I appreciate your help.
Simply, do not convert parameterized values to string as error shows single quotes:
i = 0
j = 10
cur = connection.cursor()
query = "SELECT * FROM DB.Table LIMIT %s OFFSET %s"
cur.execute(query, (j, i))
You can use cur.execute(query % (q,p)) or
query = "SELECT * FROM DB.Table LIMIT {} OFFSET {}"
cur.execute(query.format(q, p))
Related
I want to create sentiment analysis using Vader in Python and Mysql. The problem is, I got the error on mysql, especially when to insert the data into the database. The error that I got is Failed to insert record into MySQL table 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 '['compound'],'negative')' at line 2. Here are the code:
sql_select_Query = "select a from table1 union select b from table1"
cursor = connection.cursor()
cursor.execute(sql_select_Query)
records = cursor.fetchall()
for row in records:
print(row)
sid_obj = SentimentIntensityAnalyzer()
sentiment_dict = sid_obj.polarity_scores(row)
if sentiment_dict['compound'] >= 0.05 :
sentiment = 'positive'
elif sentiment_dict['compound'] <= - 0.05 :
sentiment = 'negative'
else :
sentiment = 'neutral'
mySql_insert_query = """INSERT INTO sent (q,polarity,senti) VALUES (%s,%s,%s) """
records_to_insert = [(row,sentiment_dict['compound'], sentiment)]
cursor = connection.cursor()
cursor.executemany(mySql_insert_query, records_to_insert)
connection.commit()
print(cursor.rowcount, "Record inserted successfully into table")
except mysql.connector.Error as error:
print("Failed to insert record into MySQL table {}".format(error))
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
Database table:
The problem is here:
mySql_insert_query = """INSERT INTO sent (q,polarity,senti)
VALUES (%s,sentiment_dict['compound'],'negative') """
This says you are trying to insert the string sentiment_dict['compound'], not the value it holds, into the database, which is most likely wrong. You probably want something like this (and similar for the other queries):
mySql_insert_query = """INSERT INTO sent (q,polarity,senti)
VALUES (%s,%s,'negative') """
# then later
records_to_insert = [(row, sentiment_dict['compound'])]
Or better, refactor to:
if sentiment_dict['compound'] >= 0.05 :
sentiment = 'positive'
elif sentiment_dict['compound'] <= - 0.05 :
sentiment = 'negative'
else:
sentiment = 'neutral'
mySql_insert_query = """INSERT INTO sent (q,polarity,senti)
VALUES (%s,%s,%s) """
records_to_insert = [(row, sentiment_dict['compound'], sentiment)]
(BTW, cursor.executemany() seems unnecessary since you only ever use a single set of values at a time, although I suspect you are debugging the simple case first.)
I have a dynamic sql query running in my views.py and have already ran others that work fine. I am not worried about sql injections because this is a private website. However, the parameters in my And clause has the character "|" in it which throws the error:
Unknown column "X" in 'where clause'
I have looked at solutions but they all use non dynamic query which then prohibits me from making the tablename a variable.
Here is what I want:
mycursor = mydb.cursor()
assembly_name = "peptides_proteins_000005"
group_id = 5
protein_id = "sp|P48740|MASP1_HUMAN"
qry = "SELECT * FROM %s WHERE group_id = %i AND protein_id = %s" % (assembly_name, group_id, protein_id)
mycursor.execute(qry)
But this throws the error:
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'sp' in 'where clause'
When I try doing following the answers of similar questions I get this:
qry = "SELECT * FROM %s WHERE group_id = %i AND protein_id = %s"
mycursor.exectue(qry, (assembly_name, group_id, protein_id))
However, I still get this error:
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
Changing the %i to a %s fixes the error above but then I get a new 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 ''peptides_proteins_000005' WHERE group_id = 5 AND protein_id = 'sp|P48740|MASP1_' at line 1
And here is where the loop ends, because looking up this error online suggests to write something similar to the query at the top. Can anybody help me figure out a way to do this?
For me, there was not way to do this, so I had to put literal quotes around the %s.
My final code looked something like this:
assembly_name = peptide_protein_formatter(assembly_name)
mycursor = mydb.cursor()
qry = "SELECT peptide_id,search_id FROM %s WHERE group_id = %s AND protein_id = '%s'" % (assembly_name, group_id, protein_id)
mycursor.execute(qry)
result = mycursor.fetchall()
I am trying to retrieve data from MySQL. Unfortunately, I am getting the error s below:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version fo r the right syntax to use near '1=,-5000,1)) AND
(IF(3=,5000,3)))at line 1")
volumeMin and volumeMax I put as integer. In actual, it can be float. How can I fix the error?
import MySQLdb
import MySQLdb.cursors
db = MySQLdb.connect(host='xxx.mysql.pythonanywhere-services.com',user='xxx',passwd='xxx',db='xxx$default',cursorclass=MySQLdb.cursors.DictCursor)
curs = db.cursor()
name ='G%'
volumeMin = 1
volumeMax = 3
#request args was initially want to retrieve data from external app
#but eventually found that the problem is in MySQL request
"""name = request.args['name']
volumeMin = request.args['volumeMin']
volumeMax = request.args['volumeMax']
"""
query0 = "SELECT * FROM KLSE WHERE Stock LIKE %s AND "
query2 = "(Volume_changes_pc BETWEEN (IF %s='_',-5000,%s)) AND (IF(%s='_',5000,%s)))"
query = query0+query2
input = name,volumeMin,volumeMin,volumeMax,volumeMax
print query
print input
print (query,(input))
curs.execute(query,(input))
a = curs.fetchall()
output of print (query,(input))
('SELECT * FROM KLSE WHERE Stock LIKE %s AND (Volume_changes_pc BETWEEN (IF %s=_,-5000,%s)) AND (IF(%s=_,5000,%s))) AND MACD LIKE %s ', ('G%', 1, 1
, 3, 3, 'H'))
solved
query2 = "(Volume_changes_pc BETWEEN (IF (%s='_',-5000,%s)) AND (IF(%s='_',5000,%s)))"
miss out a bracket
I am trying to make a SELECT statement to Mysql datbase using pymysql.
This is the code. I am passing a variable to the select statement, and to my surprise this is a huge pain in the lemon. Any idea what am I missing here?
def getUrlFromDatabase(n):
stmt = "SELECT * FROM jsonTes ORDER BY website LIMIT %s-1,1"
cur.execute(stmt,str(n))
return cur.fetchone()
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='passwd', db='email_database', charset='utf8')
cur = conn.cursor()
cur.execute("USE database")
getUrlFromDatabase(0)
Error:
This is what I try to achieve: Return the nth record from MySQL query
pymysql.err.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 ''0'-1,1' at line 1")
LIMIT in MySQL takes numeric arguments, which must both be nonnegative integer constants. You have to calculate the expression in Python and then pass the integer as a single parameter. Also, you need to put the parameter in a tuple:
def getUrlFromDatabase(n):
stmt = "SELECT * FROM jsonTes ORDER BY website LIMIT %s, 1"
cur.execute(stmt, (n-1 if n > 0 else 0,))
return cur.fetchone()
You are not passing the value 1 for %s in the string format.
stmt = "SELECT * FROM jsonTes ORDER BY website LIMIT %s" %n for limit n
you can use like that
def getUrlFromDatabase(n):
stmt = "SELECT * FROM jsonTes ORDER BY website LIMIT {}, 1"
cur.execute(stmt.format(n-1 if n > 0 else n))
return cur.fetchone()
I am having trouble in executing this query in python. I have an IP database which has 3 column startip, endip and country. Now I want to the location of the ip. this is my code
def get_country(ip):
try:
conn = MySQLConnection(host='localhost', database='ipdb', user ='root', password='password')
cursor = conn.cursor()
query = 'SELECT * FROM db6 WHERE %s BETWEEN INET_ATON(startip) AND INET_ATON(endip)'
ip_inint= ip2int(ip)
cursor.execute(query,ip_inint)
row = cursor.fetchone()
while row is not None:
print " Start range %s end range %s country %s " %(row[0], row[1], row[2])
row = cursor.fetchone()
except Error as error:
print(error)
ip2int function is
def ip2int(addr):
return struct.unpack("!I", socket.inet_aton(addr))[0]
error i am receiving is
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 BETWEEN INET_ATON(startip) AND INET_ATON(endip)' at line 1
what could be the issue?
You need to pass a tuple to execute():
cursor.execute(query, (ip_inint,))
A list will probably work too:
cursor.execute(query, [ip_inint])
An alternative is to use a dictionary with named variables in the query:
query = 'SELECT * FROM db6 WHERE %(ip_inint)s BETWEEN INET_ATON(startip) AND INET_ATON(endip)'
cursor.execute(query, {'ip_inint': ip_inint})
Reference: http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html