2

我搜索了很长时间的答案并做了以下事情:

(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)

但一切都不起作用......错误总是:

column "Tom" does not exist

因为它真的不存在,我只想检查它是否存在。任何帮助表示赞赏。

4

3 回答 3

3
sql = """SELECT count(*)
         FROM information_schema.columns
         WHERE table_name = '%s'
         AND column_name = '%s'
      """ % (thetable,thecolumn)
于 2012-10-19T17:38:10.163 回答
2

你没有引用你的字符串。

你的查询看起来像这样,一旦它到达 PostgreSQL:

SELECT COUNT(*) FROM Table WHERE user_name = Tom

user_name它将列与不存在的列进行比较Tom

你想要的是这样的查询:

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

要做到这一点,您应该使用参数化语句,以避免任何 SQL 注入的可能性。使用 DBAPI 模块,它很简单:

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

如果您还需要动态表名,那么您必须像这样构造它:

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

但是您需要绝对确定表名是有效的。任何可以控制该变量的人都可以对您的数据库做任何事情。

于 2012-10-19T17:38:17.643 回答
1

永远记住: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)
于 2012-10-19T17:27:11.060 回答