Related
I'm trying to create a user login system with mysql, but I can't add users, it doesn't write data to the table.
#my code
if secim == "2":
name = input ("adınız")
lastname = input ("soyadınız:")
username = input ("kullanıcı adınız:")
password = input ("Şifreniz:")
search =search_username(username)
if search != None:
print("bu kullanıcı adı ile zaten hesap var")
continue
insert(name, lastname, username, password)
print("kayıt başarılı")
if secim == "3":
break
#my server connection
def insert(name, lastname, username, password):
baglanti = pymysql.connect(host='host',
user='user',
password='password',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
cursor = baglanti.cursor()
komutekle = """INSERT INTO USERS(name, lastname, username, password) VALUES {}"""
data = (name, lastname, username, password)
cursor.execute(komutekle, data)
baglanti.commit()
baglanti.close()
Under normal circumstances, when I choose the 2nd option, it would ask me for my name, surname, username, password, but after entering them, it gives an error.
this is the error
not all arguments converted during string formatting
File "C:\Users\erpstajyer\Desktop\geleceğe dönüş\mysqlserver.py", line 42, in insert
cursor.execute(komutekle, data)
File "C:\Users\erpstajyer\Desktop\geleceğe dönüş\hesap kısmı.py", line 59, in <module>
insert(name, lastname, username, password)
TypeError: not all arguments converted during string formatting
You should pass the arguments like: VALUES(%s, %s, %s), where the %s quantity is the argument quantity in insert statement.
Code in a recommended way:
baglanti = pymysql.connect(host='host',
user='user',
password='password',
db='db')
with baglanti.cursor() as c:
komutekle = """INSERT INTO USERS(name, lastname, username,
password)
VALUES (%s, %s, %s, %s)"""
data = (name, lastname, username, password)
cursor.execute(komutekle, data)
baglanti.commit()
baglanti.close()
Using format:
with baglanti.cursor() as c:
komutekle = """INSERT INTO USERS(name, lastname, username,
password)
VALUES ({}, {}, {}, {})""".format(name, lastname, username, password)
cursor.execute(komutekle)
baglanti.commit()
baglanti.close()
passing arguments with %s avoids SQL injection.
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
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
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
I have tried 3 different variations of sqlite3 statement to SELECT a data:
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
cursor.execute('''SELECT * FROM users WHERE username = ?;''', (username,))
cursor.execute('SELECT * FROM users WHERE username = "monkey1" ')
References for these statements are from 1 2. However, none of them worked. I suspect that I am doing something really silly but can't seem to figure this out.
I want to be able to print out the data of username "monkey". Appreciate any help to point out my silly mistake.
import sqlite3
import datetime
def get_user(connection, rows='all', username=None ):
"""Function to obtain data."""
#create cursor object from sqlite connection object
cursor = connection.cursor()
if rows == 'all':
print("\nrows == 'all'")
cursor.execute("SELECT * FROM users")
data = cursor.fetchall()
for row in data:
print(row)
if rows == 'one':
print("\nrows == 'one'")
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
#cursor.execute('''SELECT * FROM users WHERE username = ?;''', (username,))
#cursor.execute('SELECT * FROM users WHERE username = "monkey1" ')
data = cursor.fetchone()
print('data = ',data)
cursor.close()
return data
def main():
database = ":memory:"
table = """ CREATE TABLE IF NOT EXISTS users (
created_on TEXT NOT NULL UNIQUE,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL UNIQUE
); """
created_on = datetime.datetime.now()
username = 'monkey'
email = 'monkey#gmail'
created_on1 = datetime.datetime.now()
username1 = 'monkey1'
email1 = 'monkey1#gmail'
# create a database connection & cursor
conn = sqlite3.connect(database)
cursor = conn.cursor()
# Insert data
if conn is not None:
# create user table
cursor.execute(table)
cursor.execute('INSERT INTO users VALUES(?,?,?)',(
created_on, email, username))
cursor.execute('INSERT INTO users VALUES(?,?,?)',(
created_on1, email1, username1))
conn.commit()
cursor.close()
else:
print("Error! cannot create the database connection.")
# Select data
alldata = get_user(conn, rows='all')
userdata = get_user(conn, rows='one', username=username )
print('\nalldata = ', alldata)
print('\nuserdata = ', userdata)
conn.close()
main()
Your table definition has the fields in order created_on, username, email but you inserted your data as created_on, email, username. Therefore the username of the first row was 'monkey#gmail'.
A good way to avoid this kind of mistake is to specify the columns in the INSERT statement rather than relying on getting the order of the original table definition correct:
INSERT INTO users (created_on, email, username) VALUES (?,?,?)