我搜索了很长时间才得到答案并做了以下事情:
(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
因为它确实不存在而且我只想检查它是否存在。任何帮助表示赞赏。
答案 0 :(得分:3)
sql = """SELECT count(*)
FROM information_schema.columns
WHERE table_name = '%s'
AND column_name = '%s'
""" % (thetable,thecolumn)
答案 1 :(得分: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)
但是你需要绝对确定表名是有效的。任何可以控制该变量的人都可以对你的数据库做任何事情。
答案 2 :(得分: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)