I need to update many rows with pyscopg based on input I receive. Input is list of tuples containing 3 elements.
input = [("Programing Langugae", "Python", "some path to img")]
_query_update = f"""UPDATE {TABLE} as t SET (category, name, img_path) = VALUES (%s, %s, %s) as t2 WHERE t.name = t2.name"""
db.cursor.executemany(_query_update, records)
db.connection.commit()
It throws me
psycopg2.errors.SyntaxError: syntax error at or near "("
LINE 1: ...ills as t SET (category, name, img_path) = VALUES ('framewor...
I need to use my middle value from the input in WHERE statement so I need to alias it somehow, because raw %s, %s, %s gives me nothing. How can I do it?
Related
I'm trying to insert some rows, but this problema occurs:
TypeError: not all arguments converted during string formatting
sql code:
f"""insert into {table} ({insert}) VALUES ({formating}) ON CONFLICT ({', '.join(key)}) DO UPDATE SET ({insert}) = ({excluded})"""
sql translate:
insert into public.atend (cd_atendimento, cd_ori_ate, cd_paciente, op_type) VALUES (%s, %s, %s, %s) ON CONFLICT (cd_atendimento) DO UPDATE SET (cd_atendimento, cd_ori_ate, cd_paciente, op_type) = (EXCLUDED.cd_atendimento, EXCLUDED.cd_ori_ate, EXCLUDED.cd_paciente, EXCLUDED.op_type)
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 ':Username, :passw, :addrss, :DOB, :emil, :ag)' at line 1
THE CODE:
def submit():
my_cursor = mydb.cursor()
#INSERT INTO TABLE
my_cursor.execute("INSERT INTO madhav VALUES (:Username, :passw, :addrss, :DOB, :emil, :ag)",
{
'Username': Username.get(),
'passw' : passw.get(),
'addrss' : addrss.get(),
'DOB' : DOB.get(),
'emil' : emil.get(),
'ag' : ag.get()
})
mydb.commit()
mydb.close()
# Clear The Text Boxes
Username.delete(0,END)
passw.delete(0,END)
addrss.delete(0,END)
DOB.delete(0,END)
emil.delete(0,END)
ag.delete(0,END)
The above function is used to insert values into a database using a GUI
That's not how you use named parameters in mydb. The correct syntax for such a parameter is %(name)s. So, in your case:
my_cursor.execute("INSERT INTO madhav VALUES (%(Username)s, %(passw)s, %(addrss)s, %(DOB)s, %(emil)s, %(ag)s)",
{
'Username': Username.get(),
'passw' : passw.get(),
'addrss' : addrss.get(),
'DOB' : DOB.get(),
'emil' : emil.get(),
'ag' : ag.get()
})
The values take type of variable, like string, integar etc.
So you code will become
stmt= (
"INSERT INTO madhav (Username, passw, addrss, DOB, emil, ag) "
"VALUES (%s, %s, %s, %s, %s, %s)"
)
Because all fielda are string type so there is %s otherwise for integar it will be %i
Next you can bound this stmt with data to execute.
data = (Username.get(), passw.get(), addrss.get(), DOB.get(),emil.get(),ag.get())
my_cursor.execute(stmt, data)
See these docs for more info
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
I want to upsert with least effort, for simplicity, i reduce columns, this not work:
sql = '''INSERT INTO temp.tickets
(id, created_at, updated_at, emails, status)
VALUES
(%s, %s, %s, %s, %s)
ON CONFLICT (id)
DO UPDATE SET ( emails, status) values (%s,%s)
'''
cursor = cm.cursor()
## cm is a custom module
cursor.execute(sql, (ticket['id'],
ticket['created_at'],
ticket['updated_at'],
ticket['emails'], ticket['status'], )
This code show Error:
return super(DictCursor, self).execute(query, vars)
IndexError: tuple index out of range
What I need to change in the cursor.execute() to work?
The Bellow code work but I like to use %s instead of type: email = excluded.email for each columns
sql = '''INSERT INTO temp.tickets
(id, created_at, updated_at, emails, status)
VALUES
(%s, %s, %s, %s, %s)
ON CONFLICT (id)
DO UPDATE SET emails = excluded.eamils, status = excluded.status
'''
cursor = cm.cursor()
# cm is a custom module
cursor.execute(sql, (ticket['id'],
ticket['created_at'],
ticket['updated_at'],
ticket['emails'], ticket['status'], )
There are two Relevant Questions link1, link2
I would try something like this:
sql = '''INSERT INTO temp.tickets
(id, created_at, updated_at, emails, status)
VALUES
(%s, %s, %s, %s, %s)
ON CONFLICT (id)
DO UPDATE SET ( emails, status) values (%s,%s)
'''
cursor = cm.cursor()
## cm is a custom module
cursor.execute(sql, (ticket['id'],
ticket['created_at'],
ticket['updated_at'],
ticket['emails'],
ticket['status'],
ticket['emails'],
ticket['status'] )
Thre number of %s must match the number of parameters.
When Postgres encounters a captured conflict it basically creates a record called EXCLUDED that contains the values you attempted to insert, You can refer to this record in DO UPDATE. Try the following:
INSERT INTO temp.tickets
(id, created_at, updated_at, emails, status)
VALUES
(%s, %s, %s, %s, %s)
ON CONFLICT (id)
DO UPDATE
SET emails = excluded.emails
, status = excluded.status
, updated_at = excluded.updated_at -- my assumption.
...
You will have to format is into the requirements of your source language.
I know this question has been asked a number of times, but i am stuck here unable to proceed further. I am executing a for loop in python to load data to fact table.
I am executing the below code
for index, row in df.iterrows():
# get songid and artistid from song and artist tables
cur.execute(song_select, (row.song, row.artist, row.length))
results = cur.fetchone()
if results:
song_id, artist_id = results
else:
song_id, artist_id = None, None
# insert songplay record
songplay_data = (pd.to_datetime(row.ts, unit='ms'),row.userId,row.level,song_id,artist_id,row.sessionId,row.location,row.userAgent)
cur.execute(songplay_table_insert, songplay_data)
conn.commit()
and getting the error
<ipython-input-22-b8b0e27022de> in <module>()
13
14 songplay_data = (pd.to_datetime(row.ts, unit='ms'),row.userId,row.level,song_id,artist_id,row.sessionId,row.location,row.userAgent)
15 cur.execute(songplay_table_insert, songplay_data)
16 conn.commit()
IndexError: tuple index out of range
My table i am trying to insert is
songplay_table_insert = ("""INSERT INTO songplays (songplay_id, start_time,
user_id, level, song_id, artist_id, session_id, location, user_agent )
VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s)
I am really stuck, any help appreciated.
You have one too many %s markers.
VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s)
has 9 markers, while
songplay_data = (pd.to_datetime(row.ts, unit='ms'),row.userId,row.level,song_id,artist_id,row.sessionId,row.location,row.userAgent)
has 8 elements. When it tries to evaluate the last marker, it looks for the 9th element, i.e. songplay_data[8], and that raises the error.
You will also need to remove songplay_id from the SQL to make the INSERT statement valid. The database should be generating the primary key for you if you don't have a value to provide, if not we should take a look at your table definition.
I'm trying to insert data that's already in one mysql table into another, using python. The column names are the same in each table, and objkey is the distinguishing piece of data I have for the item that I'd like to use to tell mysql which columns to look at.
import MySQLdb
db = MySQLdb.connect(host='', user='', passwd='', db='')
cursor = db.cursor
sql = "INSERT INTO newtable (%s, %s, %s, %s) SELECT %s, %s, %s, %s FROM oldtable
WHERE %s;" % ((name, desig, data, num), name, desig, data, num, obj = repr(objkey))
cursor.execute(sql)
db.commit()
db.close()
It says I have a syntax error, but I'm not sure where since I'm pretty sure there should be parentheses around the field names the first time but not the second one. Anyone know what I'm doing wrong?
I'm not exactly sure what you are trying to do with the obj = repr(objkey) line, but python is thinking you are defining variables with this line, not setting sql syntax (if that is indeed your desire here).
sql = "INSERT INTO newtable (%s, %s, %s, %s) SELECT %s, %s, %s, %s FROM oldtable
WHERE %s;" % ((name, desig, data, num), name, desig, data, num, obj = repr(objkey))
should probably be changed to something like:
sql = "INSERT INTO newtable (%s, %s, %s, %s) SELECT %s, %s, %s, %s FROM oldtable
WHERE obj=%;" % ((name, desig, data, num), name, desig, data, num, repr(objkey))
But even then, you would need objkey defined somewhere as a python variable.
This answer may be way off, but you need to defined what you are expecting to achieve with obj = repr(objkey), in order to get more accurate answers.