MySQL Connector could not process parameters - python

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()

Related

psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block, dont know how to fix it

I am trying to insert data into my database using psycopg2 and I get this weird error. I tried some things but nothing works. This is my code:
def insert_transaction():
global username
now = datetime.now()
date_checkout = datetime.today().strftime('%d-%m-%Y')
time_checkout = now.strftime("%H:%M:%S")
username = "Peter1"
connection_string = "host='localhost' dbname='Los Pollos Hermanos' user='postgres' password='******'"
conn = psycopg2.connect(connection_string)
cursor = conn.cursor()
try:
query_check_1 = """(SELECT employeeid FROM employee WHERE username = %s);"""
cursor.execute(query_check_1, (username,))
employeeid = cursor.fetchone()[0]
conn.commit()
except:
print("Employee error")
try:
query_check_2 = """SELECT MAX(transactionnumber) FROM Transaction"""
cursor.execute(query_check_2)
transactionnumber = cursor.fetchone()[0] + 1
conn.commit()
except:
transactionnumber = 1
""""---------INSERT INTO TRANSACTION------------"""
query_insert_transaction = """INSERT INTO transactie (transactionnumber, date, time, employeeemployeeid)
VALUES (%s, %s, %s, %s);"""
data = (transactionnumber, date_checkout, time_checkout, employeeid)
cursor.execute(query_insert_transaction, data)
conn.commit()
conn.close()
this is the error:
", line 140, in insert_transaction
cursor.execute(query_insert_transaction, data) psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block
The error message means that one of the preceding SQL statements has resulted in an error. If an exception occurs while executing an SQL statement you need to call the connection's rollback method (conn.rollback()) to reset the transaction's state. PostgreSQL will not permit further statement execution otherwise.
Ideally you want to record the actual error for later analysis, so your code ought to be structured like this:
try:
cursor.execute(sql, values)
conn.commit()
except Exception as e:
print(f'Error {e}')
print('Anything else that you feel is useful')
conn.rollback()

Str-based ValueError when using SQLite3 to import values from a variable to a database table

I'm trying to create a simple login program that saves the recorded username and password from variables into an SQLite3 database. Running the program using hardcoded strings works as expected, but when I try to use variables, a str-based TypeError occurs. I tried using str(variable), but that didn't work and I'm unsure what else could be problem. Any help would be appreciated.
import sqlite3
from sqlite3 import Error
import sys
def execute_query(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
connection.commit()
print("Query executed successfully")
except Error as e:
print(f"The error '{e}' occurred")
def create_new_user(new1, new2):
create_users = ("""INSERT INTO users (username, password)
VALUES (?, ?)
;""", str(new1), str(new2))
execute_query(connection, create_users)
create_users_table = """CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL
); """
execute_query(connection, create_users_table)
user = input("Would you like to create an account? ")
if "yes" in user:
new1 = input("\nNew username: ")
new2 = input("New password: ")
create_new_user(new1, new2)
else:
sys.exit(0)
Traceback (most recent call last):
File "/Users/scnewmark/Documents/Database/database.py", line 62, in <module>
create_new_user(new1, new2)
File "/Users/scnewmark/Documents/Database/database.py", line 40, in create_new_user
execute_query(connection, create_users)
File "/Users/scnewmark/Documents/Database/database.py", line 18, in execute_query
cursor.execute(query)
ValueError: operation parameter must be str
The execute method expects a SQL query string as the first argument and a tuple of parameters as the second argument, and yet with your:
create_users = ("""INSERT INTO users (username, password)
VALUES (?, ?)
;""", str(new1), str(new2))
and passing create_users as the query argument to do:
cursor.execute(query)
you are passing a tuple as the first argument to the execute method, resulting in the TypeError.
Instead, you can pass the query string and the parameters separately:
def execute_query(connection, query, credentials):
cursor = connection.cursor()
try:
cursor.execute(query, credentials)
connection.commit()
print("Query executed successfully")
except Error as e:
print(f"The error '{e}' occurred")
def create_new_user(new1, new2):
query = "INSERT INTO users (username, password) VALUES (?, ?);"
credentials = str(new1), str(new2))
execute_query(connection, query, credentials)

SQL Execute won't execute UCP with string format

I am trying to call this UCP I have written and it takes in some variables as input. When I run the following code, it works.
try:
cursor.execute("PYH_uspUpdateConversation #lngConversationID=1020910, #lngNodeID=2, #strText='WAZZAA', #strResponse='sup', #strSentiment=0.98")
except pyodbc.Error:
print('Error !!!!! %s' % pyodbc.Error)
print ("\nResults :")
recs = cursor.fetchall()
print(recs[0][0])
However, when I execute the same code like this:
try:
cursor.execute(f"PYH_uspUpdateConversation #lngConversationID={id}, #lngNodeID={nodeID}, #strText={text}, #strResponse={resp}, #strSentiment={sentiment}")
except pyodbc.Error:
print('Error !!!!! %s' % pyodbc.Error)
print ("\nResults :")
recs = cursor.fetchall()
print(recs[0][0])
I get an error saying that it is not a valid SQL statement: No results. Previous SQL was not a query.

Executing SQL query with psycopg2

I'm attempting to pass a list into a postgres table using psycopg2. I keep running into an exception:
File "c:/Python27/Projects/Newsletter/newsletter.py", line 148, in <module>
insert_pg(listString)
File "c:\Python27\Projects\Newsletter\pg.py", line 23, in insert_pg
print('pggggg', error)
IOError: [Errno 0] Error
The data is pretty messy (forgive me), but here's a snippet of the code. I'm running it from newsletter.py:
if __name__ == '__main__':
dataList = [today, str(int(round(float(str(spxprice.replace(',', '')))))), str(int(round(float(spxchg)))), str(int(round(float(spxpchg)))), str(int(round(float(str(dowprice.replace(',', '')))))), dowpchg, str(int(round(float(dowchg)))), str(int(round(float(str(ndxprice.replace(',', '')))))), ndxpchg, str(int(round(float(ndxchg)))), ''.join(oilPrice[4]), ''.join(getOilChg), ''.join(getOilPct), dayName]
listString = ', '.join(dataList)
insert_pg(listString)
This is pg.py, where i'm importing insert_pg from:
import psycopg2
from config import config
import sys
def insert_pg(thedata):
sql = ("""insert into prices values (%s);""" % thedata)
conn = None
try:
# read database configuration
params = config()
# connect to the PostgreSQL database
conn = psycopg2.connect(**params)
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.execute(sql)
conn.commit()
cur.close()
print 'Success.'
except (Exception, psycopg2.DatabaseError) as error:
print('pggggg', error)
finally:
if conn is not None:
conn.close()
The output of sql when I print:
insert into prices values (02/14/2018, 2675, 12, 0, 24698, 0.23, 58, 7074, 0.86, 60, 59.09, -0.06, -0.10%, Wednesday);
Not sure where i'm going wrong here. The database is connecting fine. Any ideas?
First off, you're not using bound variables which is bad practice as this can lead to SQL injection. What you should be doing is this:
cur.execute('INSERT INTO PRICES(col1, col2, ...) VALUES(%(val1)s, %(val2)s, ...)', kwargs)
where kwargs is a dictionary of key/value pairs corresponding to the column names and values. this is the correct way to do it.
The problem might be related to your attempt at printing the error by itself.
Try replacing:
print('pggggg', error) with raise.

Insert Ordered Dict values while using MySQL INSERT INTO

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)

Categories