ProgrammingError: not all arguments converted during string formatting - python

I am trying to insert a data into a BLOB column in MySQL Server it is keep giving me this error:
ProgrammingError: not all arguments converted during string formatting
I could not define why so please help,
P.S.
the type of the column in MySQL is set to LONGBLOB
here is my code:
#from mysql.connector import MySQLConnection, Error
import MySQLdb
def update_blob(filename):
# read file
pic = open(filename)
data = pic.read()
# prepare update query and data
query = "UPDATE image " \
"SET picture = ? "
print data
###############
hostname = ''
username = ''
password = ''
database = ''
try:
conn = MySQLdb.connect( host=hostname, user=username, passwd=password, db=database )
print 'connected'
cursor = conn.cursor()
cursor.execute(query, data)
conn.commit()
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
and the error:
ProgrammingError Traceback (most recent call last)
<ipython-input-35-389eb7e8c3c0> in <module>()
----> 1 update_blob('hovik.jpg')
<ipython-input-34-48db763c9aee> in update_blob(filename)
21 print 'connected'
22 cursor = conn.cursor()
---> 23 cursor.execute(query, data)
24 conn.commit()
25 except Error as e:
>/usr/lib/python2.7/dist-packages/MySQLdb/cursors.pyc in execute(self, query, args)
238 query = query % args
239 except TypeError as m:
--> 240 self.errorhandler(self, ProgrammingError, str(m))
241
242 if isinstance(query, unicode):
>/usr/lib/python2.7/dist-packages/MySQLdb/connections.pyc in defaulterrorhandler(***failed resolving arguments***)
50 raise errorvalue
51 if errorclass is not None:
---> 52 raise errorclass(errorvalue)
53 else:
54 raise Exception(errorvalue)
`ProgrammingError: not all arguments converted during string formatting`

According to the Python Database Specification in PEP 249, the format used in a query to show where to insert the parameters depends on the paramstyle member of the database module:
if it is qmark, use ? (question mark)
if it is numeric, use :1, :2 etc. (numeric, positional style)
if it is named, use :name (named style)
if it is format, use %s (ANSI C printf format codes)
if it is pyformat, use %(name)s (Python extended format codes)
AFAIR, MySQLdb uses format, so you should replace your ? with %s.
(If MySQLdb would properly use prepared statements, it would be qmark and ? was the right way to go.)

Sorted!!!! just found the solution,
1 - apparently i could not use ? because of the format specifier,
2 - and i also did not add the con for not only being able to retrive but also to insert in the database,
here is the example of the code that worked for me:
import MySQLdb
hostname = ''
username = ''
password = ''
database = ''
myConnection = MySQLdb.connect( host=hostname, user=username, passwd=password, db=database )
def doQuery() :
fin = open("hovik.jpg",'rb')
contents = fin.read()
fin.close()
with myConnection:
cur = myConnection.cursor()
sql = "INSERT INTO image VALUES (%s)"
ret = cur.execute(sql, [contents])
doQuery()
myConnection.close()

Related

Sqlite 3: Error opening the databaseIncorrect number of bindings supplied. The current statement uses 1, and there are 4 supplied

I've already tried adding in a comma after Name and the question mark in "VALUES" and was getting a syntax error for my parthenthesis.
#app.route("/Disease/new", methods = ["POST"])
def addDisease():
newDisease = {}
conn = None
try:
jsonPostData = request.get_json()
Name = jsonPostData["Name"]
conn = sqlite3.connect("./dbs/ContactTracer.db")
conn.row_factory = sqlite3.Row
sql = """
INSERT INTO Disease(Name) VALUES(?)
"""
cursor = conn.cursor()
cursor.execute(sql, (Name))
conn.commit()
sql = """
SELECT Disease.ID, Disease.Name
From Disease
Where Disease.ID = ?
"""
cursor.execute(sql,(cursor.lastrowid,))
row = cursor.fetchone()
newDisease["ID"] = row["ID"]
newDisease["Name"] = row["Name"]
except Error as e:
print(f"Error opening the database{e}")
abort(500)
finally:
if conn:
conn.close()
return newDisease
Remove the () and check if INSERT succeeded
cursor.execute(sql, Name)
...
if cursor.lastrowid:
cursor.execute(sql, cursor.lastrowid)

Python cx_Oracle binding in SQL query gives ORA-01036: illegal variable name/number

I would like to write a function that return a pandas DataFrame via an SQL query.
I have 4 agruments, the last 2 are the 'query' itself and the 'date_of_report'.
This is the query structure:
practice_query = """select * from <TABLE_NAME> b
where b.VALUE_DATE = TO_DATE(:date_of_report,'yyyy-mm-dd') """
My funtion:
import time
import cx_Oracle
import pandas as pd
def my_query(username: str = "USERNAME",
password: str = "PASSWORD",
query: str = "",
date_of_report: str = "") -> pd.DataFrame:
start = time.perf_counter()
# create connection ot EDW tables
dsn = cx_Oracle.makedsn("....", \
1112, \
service_name = "...")
conn = cx_Oracle.connect(username, password, dsn, encoding="UTF-8")
# create cursor
cur = conn.cursor()
cur.execute(query, date_of_report)
col_names = [row[0] for row in cur.description]
mydata = pd.DataFrame(cur.fetchall())
mydata.columns = col_names
end = time.perf_counter() - start
print("Run time: {:.3f}s".format(end))
return mydata
My function call:
mydata = edw_query(query = practice_query, date_of_report = "2020-09-30")
This is my error message:
DatabaseError Traceback (most recent call last)
<ipython-input-22-0ecdc646fe92> in <module>
----> 1 mydata = edw_query(query = practice_query, date_of_report = '"2020-09-30"')
<ipython-input-8-c7875fbe0d2a> in edw_query(username, password, query, date_of_report)
36 cur = conn.cursor()
37
---> 38 cur.execute(query, date_of_report)
39 col_names = [row[0] for row in cur.description]
40 mydata = pd.DataFrame(cur.fetchall())
DatabaseError: ORA-01036: illegal variable name/number
Could you help find the correct syntax? I've tried date ':date_of_report' in the SQL text where date_of_report = "2020-09-30", I've also tried :date_of_report where date_of_report = '"2020-09-30"', but nothing seems to be working.
I've found these but could not figure out a way:
https://cx-oracle.readthedocs.io/en/latest/user_guide/bind.html
https://www.techonthenet.com/oracle/functions/to_date.php
Many thanks:
Roland
Change the execute bind parameter to:
cur.execute(query, [date_of_report])
or
cur.execute(query, date_of_report=date_of_report)
See the cx_Oracle manual section Using Bind Variables. If you have suggestions on improving this doc, let us know.

how to insert values in postgresql statement, error message: not all arguments converted during string formatting

new error: near "%": syntax error
I have multiple list with values, and i want to safe them line by line in an postgresql database
i mangaged to do it with sql, but postgresql doesn´t work the same, whats the difference?
def safePsql(TrackID,seglist,trkptlist,speed,ele,time,lat,lon,hdop,mode,länge):
sql = "INSERT INTO mobilenew VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);"
#mobilenew
e = 0
modedata = []
for e in range(länge):
e= e+1
modedata.append(mode)
#vendor_list = [TrackID,seglist[f],trkptlist[f],lat[f],lon[f],ele[f],time[f],hdop[f],speed[f],modedata[f]]
try:
# read database configuration
#params = config()
# connect to the PostgreSQL database
#conn = psycopg2.connect(**params)
# create a new cursor
#cur = conn1.cursor()
conn1 = psycopg2.connect("dbname='sdb_course' user='postgres' host='localhost' password='admin'")
d = conn1.cursor()
# execute the INSERT statement
f = 0
for f in range(länge):
d.execute(sql , (TrackID,seglist[f],trkptlist[f],lat[f],lon[f],ele[f],time[f],hdop[f],speed[f],modedata[f]))
f = f+1
# commit the changes to the database
conn1.commit()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
--edited version
i hope for no error and all lines safed in psql
thanks for any help
info: the lists have all the same length, idk what wrong

Python mysql.connector error while inserting boolean into mysql database

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)

Python cx_Oracle SQL with bind string variable

I have a problem with creating SQL query for Oracle database using Python.
I want to bind string variable and it does not work, could you tell me what am I doing wrong?
This is my code:
import cx_Oracle
dokList = []
def LoadDatabase():
conn = None
cursor = None
try:
conn = cx_Oracle.connect("login", "password", "localhost")
cursor = conn.cursor()
query = "SELECT * FROM DOCUMENT WHERE DOC = :param"
for doknumber in dokList:
cursor.execute(query, {'doknr':doknumber})
print(cursor.rowcount)
except cx_Oracle.DatabaseError as err:
print(err)
finally:
if cursor:
cursor.close()
if conn:
conn.close()
def CheckData():
with open('changedNamed.txt') as f:
lines = f.readlines()
for line in lines:
dokList.append(line)
CheckData()
LoadDatabase()
The output of cursor.rowcount is 0 but it should be number greater than 0.
You're using a dictionary ({'doknr' : doknumber}) for your parameter, so it's a named parameter - the :param needs to match the key name. Try this:
query = "SELECT * FROM DOCUMENT WHERE DOC = :doknr"
for doknumber in dokList:
cursor.execute(query, {'doknr':doknumber})
print(cursor.rowcount)
For future troubleshooting, to check whether your parameter is getting passed properly, you can also try changing your query to "select :param from dual".

Categories