My postgresql database does not respond to python commands - python

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

Related

SQL Lite3 Add User

I'm trying to run a function to add a user to a flask website built with python
here is the function
def add_user(self, name, email, password, is_admin):
query = f"""
SELECT name FROM loginUsers WHERE email='{email}';
"""
response = self.conn.execute(query)
existing_user = [rec for rec in response]
if not existing_user:
created_on = datetime.utcnow()
user = User(name=name, email=email, created_on=created_on, is_admin=is_admin).set_password(password)
print(user)
query = f"""
INSERT INTO loginUsers
(name, email, created_on, password, is_admin)
VALUES
('{name}', '{email}', '{created_on}', '{pass_hashed}', {is_admin});
"""
cursor = self.conn.cursor()
cursor.execute(query)
self.conn.commit()
print('New user created')
cursor.close()
return f'User {name} - {password} is already exist'
I've tried putting in my own values multiple times and its not adding to the loginUsers table. PLEASE HELP!!!! Can this be demonstrated with example?
def add_user(self, name, email, password, is_admin):
query = f"""
SELECT name FROM loginUsers WHERE email='{email}';
"""
response = self.conn.execute(query)
existing_user = [rec for rec in response]
if not existing_user:
created_on = datetime.utcnow()
user = User(name=name, email=email, created_on=created_on, is_admin=is_admin).set_password(password)
print(user)
query = f"""
INSERT INTO loginUsers
(name, email, created_on, password, is_admin)
VALUES
('{name}', '{email}', '{created_on}', '{pass_hashed}', {is_admin});
"""
cursor = self.conn.cursor()
cursor.execute(query)
self.conn.commit()
print('New user created')
cursor.close()
return f'User {name} - {password} is already exist'
enter image description here

Check if user exists before inserting into Mysql

How do i go about something like this, I want to check if a user exists against a table in python, and if the user exists , it should report that the particular user exists, else if the user does not, it should register (insert the user into the mysql database)
So far, this is what my code is looking like
#app.route('/api/user',methods=['POST'])
def create_user():
_json = request.json
_email = _json['email']
_phone = _json['phone']
_password = _json['password']
fullname = 'NULL'
custID = '123456'
#conn = mysql.connect()
#cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor = mysql.connection.cursor()
checkuser = 'select email from accounts where email = %s' # check if user exists here.
query = "insert into accounts (email,phone,fullname,password,custID) values (%s, %s,%s, %s,%s)"
#query = "update empData set name = %s, email = %s, phone = %s, address = %s, salary = %s"
bindData = (_email, _phone, _password , fullname , custID)
cursor.execute(query,bindData)
mysql.connection.commit()
cursor.close()
output = {'email':_email, 'phone':_phone, 'fullname':fullname, 'custID':custID, 'message':'ok'}
return jsonify({'result':output}),200
How do I go about something like this, I started out flask a week ago.
Edits
This is what i been working on, but it complains about indentation. Code is looking like so
#app.route('/api/user', methods=['POST'])
def create_user():
_json = request.json
_email = _json['email']
_phone = _json['phone']
_password = _json['password']
fullname = 'NULL'
custID = '123456'
cursor = mysql.connection.cursor()
checkuser = 'select email from accounts where email = %s'
bindData = (_email)
cursor.execute(query,bindData)
acc = cursor.fetchone()
if acc:
return jsonify({'message':'User exists, Please Login'})
elif:
query = "insert into accounts (email,phone,fullname,password,custID) values (%s, %s,%s, %s,%s)"
bindData = (_email, _phone, _password , fullname , custID)
cursor.execute(query,bindData)
mysql.connection.commit()
cursor.close()
output = {'email':_email, 'phone':_phone, 'fullname':fullname, 'custID':custID, 'message':'ok'}
return jsonify({'result':output}),200
Edits 2
So I made some Edits for the second time, it just fires back Error 500 when i am testing with Postman.
My code is looking Thus
#app.route("/api/user", methods=["POST"])
def create_user():
_json = request.json
_email = _json["email"]
_phone = _json["phone"]
_password = _json["password"]
fullname = "NULL"
custID = "123456"
cursor = mysql.connection.cursor()
cursor.execute('select * from accounts where email = %s', _email)
acc = cursor.fetchone()
if acc:
return jsonify({"message": "User exists, Please Login"})
else:
query = "insert into accounts (email,phone,fullname,password,custID) values (%s, %s,%s, %s,%s)"
bindData = (_email, _phone, _password, fullname, custID)
cursor.execute(query, bindData)
mysql.connection.commit()
cursor.close()
output = {
"email": _email,
"phone": _phone,
"fullname": fullname,
"custID": custID,
"message": "ok",
}
return jsonify({"result": output}), 200
it says this is where the Error is according to the Log
which is here cursor.execute('select * from accounts where email = %s', _email) Is there something i missed?
I did a similar program a few weeks ago which is the same concept but a slightly rudamentary approach, I hope it helps.
Assuming the SQL connection was properly setup and in my case using the table "userdata" and searching the column "username"
def login(user):
cursor.execute("SELECT * FROM userdata WHERE username = '%s';" %(user,))
record = cursor.fetchone()
if record != None: # record = ('<user>','<password>')
if record[1]==password:
login_success()
else:
login_failed()
else:
data_not_found()
This activates after the button press.
login_btn = Button(root,text='Login',command=lambda:[del_failed_msg(),get_input(),login(name)])
So, here, the search result in the database should be a single record which I have stored under a variable 'record' using fetchone() function.
The fetchone() function has returned a tuple of my desired search which I can traverse to get my desired values within the record.
I got it to work!
I had to do some reading and searching thru, this gave me an idea of what to do. Its like searching thru a List or something in the Database to get adequate results
So i saw this,https://stackoverflow.com/questions/21740359/python-mysqldb-typeerror-not-all-arguments-converted-during-string-formatting
Then changed my code from this
cursor.execute('select * from accounts where email = %s', _email
to this :
cursor.execute('select * from accounts where email = %s', [_email]
And it gave the actual response I wanted it to give. Just in case it should help someone.
Thanks everyone.
Edit
Below is what the code Looks like after the work arounds.
#app.route("/api/user", methods=["POST"])
def create_user():
_json = request.json
_email = _json["email"]
_phone = _json["phone"]
_password = _json["password"]
fullname = "NULL"
custID = "123456"
cursor = mysql.connection.cursor()
cursor.execute("select * from accounts where email = %s", [_email])
acc = cursor.fetchone()
if acc:
return jsonify({"message": "User exists, Please Login"})
else:
query = "insert into accounts (email,phone,fullname,password,custID) values (%s, %s,%s, %s,%s)"
bindData = (_email, _phone, fullname, _password, custID)
cursor.execute(query, bindData)
mysql.connection.commit()
cursor.close()
output = {
"email": _email,
"phone": _phone,
"fullname": fullname,
"custID": custID,
"message": "ok",
}
return jsonify({"result": output}), 200

SQL not updating a previous entry

Still new to API's so please excuse any novice mistakes
This is where I receive the input from another port and then it gets sent to PUT method
#app.route('/PUT', methods=['POST'])
def PUT_link():
first_name = request.form['fname']
last_name = request.form['lname']
number = request.form['number']
Methods.PUT(first_name, last_name, number)
return 'success'
This is the method that should update the number but it doesn't.
#classmethod
def PUT(cls, first_name, last_name, number):
connection = sqlite3.connect('data.db')
cur = connection.cursor()
query = "UPDATE contacts SET number=? WHERE firstname=? AND lastname=?"
cur.execute(query, (first_name, last_name, number))
connection.commit()
connection.close()
return 'Contact number updated'

ValueError: Could not process parameters in Python/MySQL

I want to prevent duplicate usernames when people register.
Here is my code snippet:
def submit(self):
username_info = username.get()
username_password = password.get()
#connect to db
db = mysql.connector.connect(host = 'localhost', user = 'root', password = '', database = 'user')
#create a cursor
mycursor = db.cursor()
#insert to db
sql = ("INSERT INTO useraccess (user_type, password) VALUES (%s, %s)")
query = (username_info, username_password)
mycursor.execute(sql, query)
#commit
db.commit()
#create a messagebox
messagebox.showinfo("Registration", "Successfully Register")
#if username has been used
find_user = ("SELECT * FROM useraccess WHERE user_type = ?")
user_query = (username_info)
mycursor.execute(find_user, user_query)
#if (username == username_info):
if mycursor.fetchall():
messagebox.showerror("Registration", "The username chosen is already used. Please select another username")
else:
messagebox.showinfo("Registration", "Account Created!")
But every time I run it, although the username has been registered in the db, it only shows the successfully created messagebox and error:
ValueError: Could not process parameters.
Anyone can help me to solve this problem?
I believe the source of the problem is in the line
user_query = (username_info)
It should be
user_query = (username_info,)
The trailing comma is the syntactic difference between an expression in parentheses and a tuple.
Another issue with code is the query:
find_user = ("SELECT * FROM useraccess WHERE user_type = ?")
Which should be:
find_user = ("SELECT * FROM useraccess WHERE user_type = %s")
Have you checked these variables,
username_info = username.get()
username_password = password.get()
are they in proccesable formats? (i.e. can you directly put the username.get() into user_type ?)
I'm not familiar with this way of passing a parameter
find_user = ("SELECT * FROM useraccess WHERE user_type = ?")
have you double checked this? (why not the %s method?)
also, you probably get the "Account Created!" because mycursor.fetchall() fails.

Stored Proc no error but does not insert data in postgresql

I have Postgres as my database. I have created a function that inserts data into the postgres database (code below). MIt does not return any error but it also does not insert anything to my database. What should I change in here?
I have a model class (which is in a separate file). To use this model class (code below), I import it in my app.py.
model.py
from sqlalchemy import create_engine
import os
class DBconn:
def __init__(self):
engine = create_engine('postgresql://postgres:admin#127.0.0.1:5432/backend', echo=False)
self.conn = engine.connect()
self.trans = self.conn.begin()
def getcursor(self):
cursor = self.conn.connection.cursor()
return cursor
def dbcommit(self):
self.trans.commit()
def dbexecute(self, query, parameters):
self.conn.execute(self, query, parameters)
This is my postgres function:
function
create or replace function newcounselor(par_username text, par_password text, par_firstname text, par_middleinitial text, par_lastname text, par_contact text, par_code text, par_affiliation text, par_city text, par_done boolean) returns text as
$$
declare
loc_code text;
loc_res text;
begin
select into loc_code code from counselors where code = par_code ;
if loc_code isnull then
insert into counselors (firstname, middleinitial, lastname, contact, code, affiliation, city, done) values (par_firstname, par_middleinitial, par_lastname, par_contact, par_code, par_affiliation, par_city, par_done);
insert into users (username, password, code) values (par_username, par_password, par_code);
loc_res = 'OK';
else
loc_res = 'ID EXISTED';
end if;
return loc_res;
end;
$$
language 'plpgsql';
And in my app.py I execute that function using this python function:
def insert(sp, params, commit=True):
try:
dbo = DBconn()
cursor = dbo.getcursor()
cursor.callproc(sp, params)
cursor.callproc(dbo.dbexecute())
if commit:
dbo.dbcommit()
return
else:
return 'Error inserting data'
except Exception as e:
return str(e)
Then, to insert data using the python function, i use it this way (the username, password, etc are from my variables.. i already tested this variables and it contains my user's inputs...:
insert("newcounselor", (username, password, firstname, middleinitial,
lastname, contact, code, affiliation, city))
flash('You are now registered', 'success')
redirect(url_for('login'))

Categories

Resources