Forums

Inserting data using subqueries and python

Hello everybody,

I'm a bit new to the whole Python + DB interactions and I have encountered some issues while trying to insert into a table using subqueries. I this point I imagine it's only a problem of syntax/missing parentheses, missing exclamation marks/etc but I can't seem to be able to figure it out by myself so maybe a fresh eye could help with the issue.

This is the query I am trying to run :

 self.cur.execute("INSERT INTO game_genre (id_game, id_genre) VALUES (( SELECT gd.id_game from game_details gd where gd.title like %s, ( "%" + x + "%" , ))  , (SELECT g.id_genre from genres g where g.title_genre like %s, ("%" + genre + "%",))"))

where "x" and "genre" are variables

I have tested the queries independently (outside of the insert) and they return the expected result

Could someone shed some divine light onto this?? Thanks

There definitely is some weird quoting going on there -- if we put linebreaks to show where the strings start and stop, you have this:

self.cur.execute(
    "INSERT INTO game_genre (id_game, id_genre) VALUES (( SELECT gd.id_game from game_details gd where gd.title like %s, ( "
    %
    " + x + "
    %
    " , ))  , (SELECT g.id_genre from genres g where g.title_genre like %s, ("
    %
    " + genre + "
    %
    ",))"
))

...which is invalid syntax -- see the two brackets at the end closing a single bracket at the start. Are you getting a syntax error? If not, are you sure that's the exact code you're running?