【问题标题】:Python Psycopg2 cursor.execute returning NonePython Psycopg2 cursor.execute 返回无
【发布时间】:2016-06-22 10:23:25
【问题描述】:

您好,我正在编写一个 Python 脚本,该脚本将连接到数据库,检索一些信息并发送电子邮件。我对使用 Psycopg 完成的查询有疑问。

我想检索created_at = nb_days 所在的所有用户。我的查询在 navicat/pgadmin 中运行良好,并且我有 53 条查询记录:

select a.account_name, a.email, a.user_id, a.locale, a.firstname from v_accounts a where date(a.created_at) = date(current_date - interval '2 days') 

但是当我执行我的脚本时,我有None 作为查询的结果。这是我的脚本class

import psycopg2

class MyDatabase(object):
    db_name='you'
    user='will'
    pw='never'
    host='know'
    port='it'

    def __init__(self, db=db_name, user=user, password=pw, host=host, port=port):
        """Connection to db - creation of the cursor"""
        try:
            self.baseDonn = psycopg2.connect(host=host, port=port, database=db, user=user,password=password)
        except Exception as err:
            print('La connexion avec la base de données à échoué : Erreur détéctée : %s' % err)
        else:
            self.cursor=self.baseDonn.cursor() # Création du curseur

    def get_data_from_accounts(self,nb_days):
        ''' Method that retrieves data from all accounts that were created nb_days before today '''
        sql="select a.account_name,u.email, u.user_id,u.locale, u.firstname  from accounts a inner join account_users au on a.account_id=au.account_id inner join users u on au.user_id=u.user_id where date(a.created_at) = date(current_date - interval '%s days');"
        print(sql)
        data=(nb_days,)
        try:
            records = self.cursor.execute(sql,data)
            print('cursor-execute={}'.format(records))
        except Exception as err:
            print("La requete n'est pas passée, erreur={}".format(err))
        else:
            return records

这是主要部分

from my_db import MyDatabase
database=MyDatabase()

# On va récupérer les données des nouveaux accounts d'y a un jours
days_ago_2=database.get_data_from_accounts(2)

for personne_1 in days_ago_2:
    # data
    #account_name=personne_1[0]
    email=personne_1[1]
    user_id=personne_1[2]
    locale=personne_1[3]
    firstname='' if personne_1[4] is None else personne_1[4]

    language = locale.split('_')[1]
    activation_token= database.get_activation_token(user_id)

    subject = call_to_template2(firstname, language,activation_token)['subject']
    content = call_to_template2(firstname, language,activation_token)['content']

    print('EMAIL={} - ID={} -  LANGUE={} - FIRSTNAME={}'.format(email, user_id, language, firstname))
    #send_data(qui_envoie, email, subject, content, token, language)

我的错误在于for personne_1 in days_ago_2:,因为None object is not iterable。我已经看到了我的查询结果get_data_from_accounts(2) = None

【问题讨论】:

  • 您的 sql 字符串格式对我来说似乎很奇怪。 “print(sql)”给你什么作为输出?此外,如果您想从曾经遇到相同问题的人那里获得答案,您应该给出更准确的标题。你的标题太大了。

标签: python postgresql psycopg2


【解决方案1】:

cursor.execute 总是返回 None。你需要fetch记录集:

try:
    self.cursor.execute(sql,data)
    records = self.cursor.fetchall()

【讨论】:

  • 谢谢!对不起那个菜鸟问题我完全忘记了那个“获取”((
  • 感谢您的回答!顺便说一句,我如何打印列标题?
猜你喜欢
  • 2016-07-24
  • 2017-05-19
  • 1970-01-01
  • 2019-05-10
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-26
相关资源
最近更新 更多