I encounter this error when I'm trying to insert some values into a table.
Here's my code:
def tsx_insert(self, d_list):
for item in d_list:
query = """ INSERT IGNORE INTO tsx_first_insert(protocollo,procedura,oggetto,priorita,
tipo_richiesta,sottotipo_richiesta,emergenza,
richiesta,uo_richiedente,autore,scadenza_sla)
VALUES(%(protocollo)s,%(procedura)s,%(oggetto)s,%(priorita)s,%(tipo_richiesta)s,
%(sottotipo_richiesta)s,%(emergenza)s,%(richiesta)s,%(uo_richiedente)s,
%(autore)s,%(scadenza_sla)s)"""
values = item.values()
self.exec_query(query,values)
And here 'exec_query' function:
def exec_query(self, query, params):
try:
if self.connected is None:
self.connect()
self.cursor = self.connected.cursor()
self.cursor.connection.autocommit(True)
self.cursor.execute(query)
if self.cursor.description:
self.description = [d[0] for d in self.cursor.description]
self.rows = self.cursor.rowcount
self.sql_result = self.cursor.fetchall()
except MySQLdb.Error, e:
logging.error('Error {0}: {1}'.format(e.args[0], e.args[1]))
finally:
self.cursor.close()
The error is: "Error 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 '%(protocollo)s,%(procedura)s,%(oggetto)s,%(priorita)s,%(tipo_richiesta)s,
' at line 4"
I can't figure out what is the problem. Thank you in advance for your help.
You forgot to mention your params dictionary in your self.cursor.execute() method call, so the parameter strings were left in place rather than substituted.
Try
self.cursor.execute(query, params)
Related
I have a postgresql function that returns a string as follows:
CREATE OR REPLACE FUNCTION script.fn_indent()
RETURNS character varying
LANGUAGE 'plpgsql'
------
----function body to perform data insertion job---
results:='0 - Success';
return results
exception when others then
get stacked diagnostics
v_state = returned_sqlstate,
v_msg = message_text,
v_detail = pg_exception_detail,
v_hint = pg_exception_hint,
v_context = pg_exception_context;
raise notice 'Transaction was rolled back';
raise notice '% %', SQLERRM, SQLSTATE;
results:=v_state||'-'||v_msg||v_msg||'-'||v_detail ||'-'||v_hint ||'-'||v_context;
return results;
Now I am trying to run the above function from python using psycopg2.
conn = psycopg2.connect({connection string})
curr = conn.cursor
try:
curr.execute("SELECT * FROM script.fn_indent())
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
err = str(error)
conn.rollback()
curr.close()
print(err)
conn.close()
The above code is running fine. But I want to capture the return string from script.fn_indent() and show the same to python console. Something like as below:
---above python script---
print (results) <--results is the returning string that comes from fn_indent()
How to do it? I do not have any clue on this.
I got the clue from this thread
Refer here
Accordingly, I have modified the code base as follows:
conn = psycopg2.connect({connection string})
curr = conn.cursor
curr.execute("SELECT * FROM script.fn_indent()")
conn.commit()
s = curr.fecthone()
print (s)
conn.close()
I am running a Stored Procedure to insert a new row into a table and return the Auto-Generated ID.
However, it doesn't insert the row but does respond correctly with the id when calling it from Python. (Eg it returns 9 but when looking in the DB where is no new message)
Running the command using SQL Workbench does work as expected
The SP being called is addNewMessage and expects 3 parameters(sUID, roomid, message)
SQL command (when running manually)
CALL addNewMessage('bfc1cc8c-4462-11ea-887c-000d3a7f4c7f', '658946602274258955', 'My Message')
SQL SP
BEGIN
INSERT INTO `messages`(`server_uid`, `title`, `message`, `author`, `room_id`) VALUES (sUID,title,'','',room);
SELECT ##IDENTITY as newId;
END
Python Scripts
new_message = mysql_command('discord_addNewMessage', ['bfc1cc8c-4462-11ea-887c-000d3a7f4c7f', '658946602274258955', 'My Message'])
print(new_message);
def mysql_command(command, args, addDataWrapper=False, decode=False):
global sql_cursor
try:
if isinstance(args, list):
sql_cursor.callproc(command, [arg for arg in args])
else:
sql_cursor.callproc(command, [args])
for result in sql_cursor.stored_results():
return_data = result.fetchall()
if decode:
data = return_data[0][0].decode('utf-8')
else:
data = return_data[0][0]
if addDataWrapper:
data = '{"data":[' + data + ']}'
return data
except BaseException as ex:
print("SQL Error :", ex)
After some more digging, I needed to commit using mydb.commit() after the sql_cursor.callproc
I'm trying to loop through an array and insert each element into a table. As far as I can see my syntax is correct and I took this code straight from Microsoft Azure's documentation.
try:
conn = mysql.connector.connect(**config)
print("Connection established")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with the user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cursor = conn.cursor()
data = ['1','2','3','4','5']
for x in data:
cursor.execute("INSERT INTO test (serial) VALUES (%s)",(x))
print("Inserted",cursor.rowcount,"row(s) of data.")
conn.commit()
cursor.close()
conn.close()
print("Done.")
When I run this is gets to cursor.execute(...) and then fails. Here is the stack trace.
Traceback (most recent call last):
File "test.py", line 29, in
cursor.execute("INSERT INTO test (serial) VALUES (%s)",("test"))
File "C:\Users\AlexJ\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\cursor_cext.py", line 248, in execute
prepared = self._cnx.prepare_for_mysql(params)
File "C:\Users\AlexJ\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\connection_cext.py", line 538, in prepare_for_mysql
raise ValueError("Could not process parameters")
ValueError: Could not process parameters
Try this:
for x in data:
value = "test"
query = "INSERT INTO test (serial) VALUES (%s)"
cursor.execute(query,(value,))
print("Inserted",cursor.rowcount,"row(s) of data.")
Since you are using mysql module, cursor.execute requires a sql query and a tuple as parameters
Nice answer from #lucas, but maybe this help other, cz i think more cleaner
sql = "INSERT INTO your_db (your_table) VALUES (%s)"
val = [("data could be array")]
cursor = cnx.cursor()
cursor.execute(sql, val)
print("Inserted",cursor.rowcount,"row(s) of data.")
cnx.commit()
cnx.close()
Cz this is useful for my purpose, to input multiple data.
I'm facing same issue but instead of array, I'm looping through a set and insert each item into mysql db and got this error mysql.connector.errors.ProgrammingError: Could not process parameters: str(Data_Tokens), it must be of type list, tuple or dict.
The uniqueTokenSet includes string data type, but as error shows that it must be list, tuple or dict. By converting item to list of tuple [(item)] work for me.
uniqueTokenSet = set()
for item in uniqueTokenSet:
tokenSql = "insert into tokens(token) values (%s)"
data = [(item)]
mycursor.execute(tokenSql, data)
print('data inserted')
mydb.commit()
In the code below, I am trying to insert a boolean value in Network table, where the status field is declared as boolean.
import urllib2
import mysql.connector as conn
import MySQLdb
import logging
class getData:
#staticmethod
def checkNetwork():
try:
urllib2.urlopen('https://www.google.com', timeout = 2)
return True
except urllib2.URLError as err:
return False
#staticmethod
def connectDB():
db = conn.connect(host='****', user='****', passwd='****', db='*******')
cursor = db.cursor()
return db,cursor
#staticmethod
def insertNData(data):
print type(data)
db,cursor = getData.connectDB()
sql_Query = "INSERT INTO Network(status) VALUES(%s);"
try:
result= cursor.execute(sql_Query,data)
db.commit()
logging.warn("%s", result)
logging.info("Success")
except MySQLdb.IntegrityError:
logging.warn("Failed")
finally:
db.close()
return True
netStat = getData.checkNetwork()
getData.insertNData(netStat)
When I run the code, I get the below error
ERROR 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
I tried searching on google to find some solution and also changed a few things to test but still the same error.
Thanks in advance.
There is error in this line:
sql_Query = "INSERT INTO Network(status) VALUES(%s);"
You are not passing the value correctly. You created a placeholder but did not fill it.
Use:
for python3.6 and above:
sql_Query = f"INSERT INTO Network(status) VALUES({data});"
for python 2 and 3:
sql_Query = "INSERT INTO Network(status) VALUES({});".format(data)
or
sql_Query = "INSERT INTO Network(status) VALUES(%s);" %(data)
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