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 (?,?,?)
Related
What I am trying to do is to get the email id and compare against the SQLite table.
If email exists in the table then I update the table with the emailid and random generated password and mail them.
If email does not exists in the table then I use insert query to enter the email as well as random generated password into the table.
After the insert or the update query is fired I mail them the generated password using Flask-mail
However I am unable to execute it
def sqliteconfig():
try:
conn = sqlite3.connect('auth.db',check_same_thread=False)
cur = conn.cursor()
conn.execute('CREATE TABLE IF NOT EXISTS auth (AID INTEGER PRIMARY KEY AUTOINCREMENT, emailid TEXT UNIQUE, otp TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP)')
cur.close()
except Exception as e:
print(e)
return 'DatabaseDown'
# return 'DatabaseDown'
return conn
#bp.route('/')
def index_redirect():
return redirect(url_for('devcon.login'))
#bp.route('/login',methods=['GET','POST'])
def login():
conn = sqliteconfig()
cur = conn.cursor()
if request.method == 'POST':
emailid = request.form['emailid']
if emailid != "":
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
passlen = 8
password = "".join(random.sample(s,passlen ))
conn.execute('select count(*) from auth where emailid=(?)',[emailid])
rows = cur.fetchall();
if len(rows) == 0:
conn.execute('insert into auth(email,otp) values(?,?)',[emailid,password])
conn.commit()
elif len(rows)==1:
conn.execute('update auth SET otp=(?) where emailid=(?)',[emailid,password])
conn.commit()
return str(rows)
return render_template("login/login.html")
The Particular problem I am facing right know is SELECT COUNT query returns nothing and INSERT query throws constraint violation error of unique emailid.
I am looking forward if there is any better way to do this
For the first error where SELECT COUNT returns nothing, in Sqlite3 select * is used instead of select count(*). Therefore your code should be:
rows = conn.execute('SELECT * FROM auth WHERE emailid = ?',(emailid,)).fetchall()
For the second insertion error, you may already have an equivalent emailid value stored into auth. That is the only reason why you would have a constraint violation of an unique emailid.
Another (potential) error is that you set otp to emailid and password to emailid, while the order should be reversed:
conn.execute('update auth SET otp=(?) where emailid=(?)',[emailid,password])
Instead, do this:
conn.execute('UPDATE auth SET otp = ? WHERE emailid = ?',(password, emailid))
Final code:
def sqliteconfig():
try:
conn = sqlite3.connect('auth.db',check_same_thread=False)
cur = conn.cursor()
conn.execute('CREATE TABLE IF NOT EXISTS auth (AID INTEGER PRIMARY KEY AUTOINCREMENT, emailid TEXT UNIQUE, otp TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP)')
cur.close()
except Exception as e:
print(e)
return 'DatabaseDown'
# return 'DatabaseDown'
return conn
#bp.route('/')
def index_redirect():
return redirect(url_for('devcon.login'))
#bp.route('/login',methods=['GET','POST'])
def login():
conn = sqliteconfig()
cur = conn.cursor()
if request.method == 'POST':
emailid = request.form['emailid']
if emailid != "":
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
passlen = 8
password = "".join(random.sample(s,passlen ))
rows = conn.execute('SELECT * FROM auth WHERE emailid = ?',(emailid,)).fetchall()
if len(rows) == 0:
conn.execute('INSERT into auth (email, otp) VALUES (?, ?)',(emailid, password))
conn.commit()
elif len(rows)==1:
conn.execute('UPDATE auth SET otp = ? WHERE emailid = ?',(emailid, password))
conn.commit()
return str(rows)
return render_template("login/login.html")
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.
When I create the DataBase CURRENT_users.db:
import sqlite3
conn = sqlite3.connect('CURRENT_users.db')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome TEXT NOT NULL,
email TEXT NOT NULL,
created_in DATE NOT NULL,
password TEXT NOT NULL
)
""")
print("Success! DATABASE created with success!")
conn.close()
import UserLoginUI_Part2_Tes
t1
And I insert the DATA:
import sqlite3
conn = sqlite3.connect("CURRENT_users.db")
cursor = conn.cursor()
cursor.execute("""
INSERT INTO users (id, nome, email, created_in, password)
VALUES (001, "Renatinho", "renato.lenon#Outlook.com", 2005-4-21, "Plugxyvj9");
""")
conn.commit()
print("A new user has been incremented! Now,have fun!!!")
conn.close()
import UserInterface
In "UserInterface", I type "Renatinho" (that's my NOME data),it seems like that "IF" doesn't work!!
import sqlite3
conn = sqlite3.connect("CURRENT_users.db")
cursor = conn.cursor()
user_INFO = cursor.execute(""" SELECT nome FROM users; """)
user_in_SCRIPT = str(input("Your credentials: USERNAME: \n>>>"))
logged_in = False;
if user_in_SCRIPT == user_INFO:
print("You are logged in! Enjoy your new account...")
logged_in = True;
else:
print("Error: Not a valid user or USERNAME!!")
conn.close()
And it ever shows me the ELSE "command block"..
Please,who can help me?
Thanks for everything...
PRINT OF THE ERROR:
You've called SQL SELECT but you need to fetch the data.
cursor.execute("SELECT nome FROM users")
user_INFO = cursor.fetchone()
This would return a tuple, so to get the string inside, take the zero index:
if user_in_SCRIPT == user_INFO[0]:
print("You are logged in! Enjoy your new account...")
logged_in = True
BTW, you're in Python, not JavaScript. You don't need to end statements with semicolons. :-)
I am trying to query whether the staff ID and password are correct. The query works, however I want to get the fname and lname data from the database and print certain fields. It seems as though the row[fname] and row[lname] doesn't work... is there another way to do this? I keeps saying fname is not defined.
import sqlite3
connection = sqlite3.connect('shop.db')
cursor = connection.cursor()
create_table = '''
CREATE TABLE IF NOT EXISTS employee (
staff_ID INTEGER PRIMARY KEY,
password CHAR(4),
fname VARCHAR(20),
lname VARCHAR(30));'''
cursor.execute(create_table)
staffid = input('staff id: ')
password = input('password: ')
cursor.execute('SELECT * FROM employee WHERE staff_ID=? AND password=?', [staffid, password])
row = cursor.fetchone()
if row != None:
print(row[fname]+' '+row[lname])
You may insert any values into this table, I just didn't want the code to look too bulky... Thanks!
I have the following function:
def credential_check(username, password):
conn = sqlite3.connect('pythontkinter.db')
c = conn.cursor()
idvalue = c.execute('''SELECT ID FROM userdetails WHERE username = "{0}"'''.format(username)).fetchall()
print(idvalue)
I wish to assign the value of ID in my userdetails table to the variable idvalue in the row where the inputted username = userdetails username, however when I use this fetchall() I get [('0',)] printed out rather than just 0.
How do I go about doing this?
Thanks
You can use fetchone() if you only want one value. However, the result will still be returned as a tuple, just without the list.
import sqlite3
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS testing(id TEXT)''')
conn.commit()
c.execute("""INSERT INTO testing (id) VALUES ('0')""")
conn.commit()
c.execute("""SELECT id FROM testing""")
data = c.fetchone()
print data
# --> (u'0',)
You can also use LIMIT if you want to restrict the number of returned values with fetchall().
More importantly, don't format your queries like that. Get used to using the ? placeholder as a habit so that you are not vulnerable to SQL injection.
idvalue = c.execute("""SELECT ID FROM userdetails WHERE username = ?""", (username,)).fetchone()