简体   繁体   中英

PostgreSQL query gives unexpected result

I'm trying to do something extremely simple that works, but not the way I expect it to. I have a database with various tables and for each of those tables, I'm trying to extract the column names from the information schema. I'm using the code below and everything works like a charm (python):

import psycopg2 as pgsql

# code to connect and generate cursor

table = 'some_table_name'

query = 'SELECT column_name FROM information_schema.columns WHERE table_name = %s'

cursor.execute(query, (table,))
result = pd.DataFrame(cursor.fetchall())
print(result)

So far, so good. The problem arises when I replace the query variable with the following:

import psycopg2 as pgsql

# code to connect and generate cursor

table = 'some_table_name'

**query = 'SELECT column_name FROM information_schema.columns WHERE table_name='+table

cursor.execute(query)**
result = pd.DataFrame(cursor.fetchall())
print(result)

If I print the statement, it's correct:

SELECT column_name FROM information_schema.columns WHERE table_name=some_table_name

However, when I run the query, I'm getting this error message:

UndefinedColumn: column "some_table_name" does not exist
LINE 1: ... FROM information_schema.columns WHERE table_name=some_tabl...

some_table_name is a table name as a parameter to the WHERE clause, not a column name. How is this even possible?

Thanks!

Your problem is that you haven't put some_table_name in quotes so it is treated as a column name, not a string literal. Why not stick with the first method which both worked and is in line with the psycopg documentation?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM