简体   繁体   English

使用Python检查PostgreSQL表中是否存在一列

[英]Check if a column exists in PostgreSQL table using Python

I searched for a long time for the answer and did the following: 我搜索了很长时间以寻找答案,并做了以下工作:

(1) (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) (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) (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: 一旦查询到PostgreSQL,您将查询如下:

SELECT COUNT(*) FROM Table WHERE user_name = Tom

Which compares the user_name column against the non-existant Tom column. user_name列与不存在的Tom列进行比较。

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. 为此,您应该使用参数化语句,以避免SQL注入的任何可能性。 With a DBAPI module, it's a simple as: 使用DBAPI模块,它很简单:

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 永远记住: 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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