0

Hello I am getting error from my code, can someone help me please?

def query_builder(self, field_name, table_name, pkey, id):

    queryx=sql.SQL("select {field} from {table} where {pkey} = %s",(id)).format(
        field=sql.Identifier(field_name),
        table=sql.Identifier(table_name),
        pkey=sql.Identifier(pkey))
    
    self.cur.execute(queryx.as_string(self.conn))

1 Answer 1

1

I'm going to assume you are using psycopg2.

If so the issues are, first:

"select {field} from {table} where {pkey} = %s",(id) ..."

Do not include the argument (id) in the string. Also this is not proper form for a single value in a tuple. Python requires it be (id,), note the comma.

Second:

self.cur.execute(queryx.as_string(self.conn))

Should be:

self.cur.execute(queryx, (id,))

The execute is where you supply the argument. Also the composable sql.SQL(...) can be passed directly to execute without being run through as_string. See here sql for more examples.

UPDATE

To use "*" there are two ways:

cur.execute(sql.SQL("select * from {table} where {pkey} = %s).format(table.sql.Identifier(table_name), pkey=sql.Identifier(pkey))

--OR

cur.execute(sql.SQL("select {field} from {table} where {pkey} = %s).format(field=sql.SQL("*"), table=sql.Identifier(table_name), pkey=sql.Identifier(pkey))

Warning, the second does allow for SQL injection as sql.SQL() does not escape values.

As to multiple fields the sql section of the docs has multiple examples. For instance:

If part of your query is a variable sequence of arguments, such as a comma-separated list of field names, you can use the SQL.join() method to pass them to the query:

query = sql.SQL("select {fields} from {table}").format(
    fields=sql.SQL(',').join([
        sql.Identifier('field1'),
        sql.Identifier('field2'),
        sql.Identifier('field3'),
    ]),
    table=sql.Identifier('some_table'))
Sign up to request clarification or add additional context in comments.

6 Comments

Adrian thank yo so much, it really works. I appreciate it. I have 2 short questions 1)what if I want to obtain all the fields? When I send "*" argument into the field_name parameter I receive an error. 2)If I want to obtain multiple fields like FullName, EmailAddress, how to structure the arguments?
Yes, I do use psycopg2, Than you so much.
I understand thank so much for your time, Adrian. It is very clear.
If it answers your question will you accept the question and/or upvote it?
Hi Adrian, of course I would. I was searching for where I can upvote for you, I am new in stackoverflow.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.