简体   繁体   中英

Check if a column exists in PostgreSQL table using Python

I searched for a long time for the answer and did the following:

(1)

query = "SELECT COUNT(*) FROM %s WHERE user_name = %s" % (table_name, username)
result = conn.query(query).result()[0][0]
if result == 0:
    (do something)

(2)

query = "SELECT 1 FROM %s WHERE user_name = %s" %(table_name, username)
result = conn.query(query).result()[0][0]
if result == ' ':
    (do something)

(3)

query = "SELECT EXISTS (SELECT 1 FROM %s WHERE user_name = %s)" %(table_name, username)
result = conn.query(query).result()[0][0]
if result == 't':
    (do something)

But all don't work... the error is always:

column "Tom" does not exist

Since it really doesn't exist and I just want to check if it exists. Any help is appreciated.

sql = """SELECT count(*)
         FROM information_schema.columns
         WHERE table_name = '%s'
         AND column_name = '%s'
      """ % (thetable,thecolumn)

You're not quoting your strings.

You query looks like this, once it gets to PostgreSQL:

SELECT COUNT(*) FROM Table WHERE user_name = Tom

Which compares the user_name column against the non-existant Tom column.

What you want is a query like this:

SELECT COUNT(*) FROM Table WHERE user_name = 'Tom'

To do this right, you should be using parameterized statements, to avoid any possibility of SQL injection. With a DBAPI module, it's a simple as:

cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM Table WHERE user_name = %s', user_name)

If you need the table name to be dynamic as well, then you have to construct it like this:

cursor = conn.cursor()
query = 'SELECT COUNT(*) FROM %s WHERE user_name = %%s' % table_name
cursor.execute(query, user_name)

But you need to be absolutely certain that the table name is valid. Anybody who could control that variable could do absolutely anything to your database.

Always remember: EAFP

try:
   result = conn.query(query).result()
except ProgrammingError:  # Edumacated guess based on the documentation
   # however untested so psycopg2 raises some other instead
   pass # or do_something_when_it_does_not_exist()
else:
   (do something)

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