简体   繁体   中英

My postgresql database does not respond to python commands

I am applying SQL commands with Python (PyCharm), and for some reason that I can't understand the following method can't be executed:

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()

It is called from the following script:

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()

Neither the database is updated, nor the print command I use as a trace is giving any outcome in the run window of pycharm. Even if I use a non valid password, instead of an error I get "Process finished with exit code 0". However that method worked once, the first time I applied it, allowing me to save some data in the database. Since then I get response from the database only through pgadmin4. I would be glad if I could get some help about this issue. Thank you in advance.

There may be some more details in the previous thread I raised for the same issue: python-postgresql, seems to be connected but no respond

EDIT: I'm placing the full code of the application. The file with the User class is following:

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])

And here is following the file which is calling both of the two methods.

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)

Again I'm using a print method as a trace, and what it comes is that also the code that's calling the methods is not executed.

It looks like an exception is being generated and you are not seeing it. Or some code that is wrapping this function is catching it with except: and not reporting it.

How about this varient:

EDIT: Added a couple of print()s.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM