psycopg2 not all arguments converted during string formatting

2024/10/13 21:19:51

I am trying to use psycopg2 to insert a row into a table from a python list, but having trouble with the string formatting.

The table has 4 columns of types (1043-varchar, 1114-timestamp, 1043-varchar, 23-int4). I have also made attempts with 1082-date instead of timestamp, and 21-int2 instead of int4.

The following statement works fine in pgAdmin or through a psycopg2 cursor execution without string formatting:

INSERT INTO ssurgo.distmd VALUES ('5', '2015-01-01', 'Successful', 4891);

However, if I do:

sql_text = "INSERT INTO ssurgo.distmd VALUES %s ;"
data  = ['5', '2015-01-01', 'Successful', 4891]
data[1] = date.today() # ensure psycopg2 recognizes a date using datetime
print(curs.mogrify(sql_text, data))

I get:

TypeError: not all arguments converted during string formatting

I get the same error if I keep the date as a '2015-01-01' string instead of a datetime.date object, and if I use curs.execute(sql_text, data) rather than mogrify.

I am passing a list, so I don't think this is related to the more common single tuple error I found in other questions that is necessary to create a non-string sequence, and explicitly converting to a tuple did not fix the error.

Does anyone know why the psycopg2 string formatting is giving an error?

Answer

You can keep your original code but pass a tuple in instead of a list:

sql_text = "INSERT INTO ssurgo.distmd VALUES %s ;"
data  = ('5', date.today(), 'Successful', 4891)
print(curs.mogrify(sql_text, [data]))

Notice that you are passing a single value so it is necessary to wrap it in an iterable which is what Psycopg expects. The tuple will be adapted by Psycopg to the correct values syntax: a record

https://en.xdnf.cn/q/118037.html

Related Q&A

inherited function odoo python

i want to inherit function in module hr_holidays that calculate remaining leaves the function is :hr_holiday.py:def _get_remaining_days(self, cr, uid, ids, name, args, context=None):cr.execute("&…

ValueError in pipeline - featureHasher not working?

I think Im having issues getting my vectorizer working within a gridsearch pipeline:data as panda df x_train:bathrooms bedrooms price building_id manager_id 10 1.5 3 3000 53a5b119b…

pandas dataframe: meaning of .index

I am trying to understand the meaning of the output of the following code:import pandas as pdindex = [index1,index2,index3] columns = [col1,col2,col3] df = pd.DataFrame([[1,2,3],[1,2,3],[1,2,3]], index…

Extract text inside XML tags with in Python (while avoiding p tags)

Im working with the NYT corpus in Python and attempting to extract only whats located inside "full_text" class of every .xml article file. For example: <body.content><block class=&qu…

Python (Flask) and MQTT listening

Im currently trying to get my Python (Flask) webserver to display what my MQTT script is doing. The MQTT script, In essence, its subscribed to a topic and I would really like to categorize the info it …

I dont show the image in Tkinter

The image doesnt show in Tkinter. The same code work in a new window, but in my class it does not. What could be the problem ?import Tkinterroot = Tkinter.Tkclass InterfaceApp(root):def __init__(self,…

Read temperature with MAX31855 Thermocouple Sensor on Windows IoT

I am working on a Raspberry Pi 2 with Windows IoT. I want to connect the Raspberry Pi with a MAX31855 Thermocouple Sensor which I bought on Adafruit. Theres a Python libary available on GitHub to read …

PIP: How to Cascade Requirements Files and Use Private Indexes? [duplicate]

This question already has an answer here:Installing Packages from Multiple Servers from One or More Requirements File(1 answer)Closed 9 years ago.I am trying to deploy a Django app to Heroku where one …

Python error: TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

Below is a small sample of my dataframe. In [10]: dfOut[10]:TXN_KEY Send_Agent Pay_Agent Send_Amount Pay_Amount 0 13272184 AWD120279 AEU002152 85.99 85.04 1 13272947 ARA03012…

How to remove grey boundary lines in a map when plotting a netcdf using imshow in matplotlib?

Is it possible to remove the grey boundary lines around the in following map? I am trying to plotting a netcdf using matplotlib.from netCDF4 import Dataset # clarify use of Dataset import matplotlib.p…