我需要编写一个程序,首先,可以查看在google上查看我的广告系列的人的IP地址,然后向我提供有关这些人的详细信息。
我在postgres数据库中有所有信息并使用python 3.5
这是我的代码:
def get_connection(cursor_factory=None):
conn_string_pg = "host= '" + host + "' dbname = '" + dbname + "' user = '" + user + \
"' password = '" + password + "'"
if cursor_factory is None:
conn_pg = psycopg2.connect(conn_string_pg)
else:
conn_pg = psycopg2.connect(conn_string_pg,
cursor_factory=cursor_factory)
return conn_pg
def find_logs():
select = """ select ip_address from log_files o where o.url like
'%my_campaign'
"""
conn = get_connection(cursor_factory = RealDictCursor)
cur = conn.cursor()
cur.execute(select)
records = cur.fetchone()
for item in records:
select_2 = "select * from log_files where ip_address = %(item)s "
cur.execute(select_2)
logs = cur.fetchone()
return logs
print(find_logs())
cur.close()
不幸的是我收到了这个错误:
psycopg2.ProgrammingError:语法错误在或附近"%"第1行: ...从web_logs.log_data中选出*,其中ip_address =%(item)s o ...
答案 0 :(得分:0)
这是因为ip_address = %(item)s
它不是有效的sql语法。你应该在之前进行字符串格式化:
select_2 = "select * from log_files where ip_address = %(item)s " % {'item': item}
更好的方法是将所有转换都提供给postgres驱动程序
select_2 = "select * from log_files where ip_address = %s "
cur.execute(select_2, (item, ))
答案 1 :(得分:0)
您的字符串插值不正确。您试图将item的值插入到select_2
语句中,但实际上并没有进行字符串插值,因此您将psycopg2传递给无效的SQL语句。你想做类似
select_2 = "select * from log_files where ip_address = {}".format(item)