我的Postgresql数据库不响应python命令

时间:2018-12-12 00:23:58

标签: python postgresql psycopg2

我正在通过Python(PyCharm)应用SQL命令,由于某种原因,我不明白无法执行以下方法:

def save_to_db(self):
    connection = psycopg2.connect(user='postgres', password='valid', database='learning', host='localhost')
    with connection.cursor() as cursor:
        cursor.execute('INSERT INTO users (email, first_name, last_name) VALUES (%s, %s, %s)',(self.email, self.first_name, self.last_name))
    print('here save_to_db')    # as a trace
    connection.commit()
    connection.close()

它是从以下脚本中调用的:

from user import User    # the class where the methods are
my_user = User('email@email.com', 'first name', 'last name', None)  # in the database there is auto-increment for the primary key (4th argument)
my_user.save_to_db()

数据库没有更新,我用作跟踪的打印命令都没有在pycharm的运行窗口中给出任何结果。即使我使用无效的密码,也不会出现错误,而是显示“进程以退出代码0完成”。但是,该方法一次有效,这是我第一次应用它,使我可以在数据库中保存一些数据。从那时起,我仅通过pgadmin4从数据库获得响应。 如果能在此问题上获得帮助,我将感到非常高兴。预先谢谢你。

在我针对相同问题提出的上一个线程中可能还有更多详细信息: python-postgresql, seems to be connected but no respond

编辑:我要放置应用程序的完整代码。 带有User类的文件如下:

import psycopg2


class User:
def __init__(self, email, first_name, last_name, id):
    self.email = email
    self.first_name = first_name
    self.last_name = last_name
    self.id = id

def __repr__(self):
    return "<User {}>".format(self.email)

def save_to_db(self):
    with psycopg2.connect(user='postgres', password='valid', database='learning', host='localhost')
        with connection.cursor() as cursor:
            cursor.execute('INSERT INTO users (email, first_name, last_name) VALUES (%s, %s, %s)', (self.email, self.first_name, self.last_name))
    print('here save_to_db')    # as a trace to define wether or not the method is executed


@classmethod
def load_from_db_by_email(cls, email):
    with psycopg2.connect(user='postgres', password='valid', database='learning', host='localhost') as connection:
        with connection.cursor() as cursor:
            cursor.execute('SELECT * FROM users WHERE email=%s', (email,))
            user_data = cursor.fetchone()
            return cls(user_data[1], user_data[2], user_data[3], user_data[0])

下面是同时调用这两种方法的文件。

from user import User

saveToDb = 1 # 1 to save, else to load

if saveToDb==2:
    print('save')    # a print method again as a trace
    my_user = User('email@email.com', 'first_name', 'last_name', None)
    my_user.save_to_db()
else:
    print('load')    # a print method again as a trace
    my_user = User.load_from_db_by_email('email@email.com')
    print(my_user)

同样,我使用打印方法作为跟踪,结果是调用该方法的代码也没有执行。

1 个答案:

答案 0 :(得分:0)

似乎正在生成异常,您没有看到它。或者包装此函数的某些代码正在用except:捕获它,而没有报告它。

该变量如何:

编辑:添加了几个print()。

def save_to_db(self):
    print("DEBUG: ENTER save_to_db()");
    rc = False
    my_database = 'learning'
    try:
        connection = psycopg2.connect(user='postgres', password='zSvG3$', database=my_database, host='localhost')
    except Exception as e:
        print("Unable to connect to [" + my_database + "] - " + str(e))
        connection = None

    if (connection != None):
        cursor = connection.cursor()
        try:
            cursor.execute('INSERT INTO users (email, first_name, last_name) VALUES (%s, %s, %s)',  (self.email, self.first_name, self.last_name))
            connection.commit()
            connection.close()
            rc = True
        except Exception as e:
            print("INSERT FAILED - "+str(e))
    print("DEBUG: EXIT save_to_db()");
    return rc