python
  • postgresql-9.4
  • 2017-06-16 46 views -2 likes 
    -2

    我需要編寫一個程序,它可以首先爲在Google上看到我的廣告系列的人的ip地址,然後向我提供關於這些人員的詳細信息。python 3.5選擇和使用來自postgres數據庫的結果

    我在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: syntax error at or near "%" LINE 1: ...elect * from web_logs.log_data where ip_address = %(item)s o...

    回答

    0

    你的串插不正確。您試圖將項目的值插入到select_2語句中,但實際上並未進行字符串插值,因此您將psycopg2傳遞給了無效的SQL語句。你想要做類似

    select_2 = "select * from log_files where ip_address = {}".format(item) 
    
    +0

    非常感謝你,亞歷克斯。它工作完美! – julira

    0

    這是因爲ip_address = %(item)s它不是一個有效的sql語法。你應該讓之前的字符串格式化:

    ​​3210

    而更好的方式來做到這一點是讓所有的轉換到Postgres的司機

    select_2 = "select * from log_files where ip_address = %s " 
    cur.execute(select_2, (item,)) 
    
    +0

    感謝Oleksandr的快速回復。第二種解決方案很好,但與cur.execute(select_2,項['ip_address'])我收到一個錯誤:TypeError:字符串索引必須是整數 – julira

    相關問題