I am trying to select a value from my python SQL table based on a variable that the user inputs, through Tkinter. My database has a column named employee_username and has the employee's usernames and their password in 1 row. Username is entered by the user in a tkinter window
My code looks like this:
import sqlite3
import password_database
import tkinter
conn = sqlite3.connect('passwordDb.db')
c = conn.cursor()
username=entry_user.get()
password=entry_user.get()
database_username=c.execute(SELECT * FROM passwordDb WHERE
employee_username=username)
if database_username!=' ':
print('you entered a username which is not in the database')
else:
running=True
When I run this code I am not able to get any results. How do I manage to check if the value the user enters is in my database and how to I retrieve employee's password attached to the username.
Thanks in advance
Your code is not complete but I guess i understand you.
Before you query the database, you need to strip of white spaces from the username or the input
username = input("username")
db_username = username.strip() #this removes the white space
# you can then check to see if the username is none...
records = cur.fetchall(); # this would return all matching records, loop through
if not database_user is None:
...
else:
print("your username is bad")
I see few mistakes
First: query should be as string, and it should have ? and username should be tuple (username, ) as argument
c.execute("SELECT * FROM passwordDb WHERE employee_username=?", (username, ))
Second: you have to use fetchall() or fetchone()` to get list with results or first result.
rows = cur.fetchall()
row = cur.fetchone()
Third: execute() doesn't have to return value so there is no sense to comparer with string " ". fetchall()/fetchone()` returns row(s) with result(s) so you can check how many rows it returned.
rows = cur.fetchall()
if len(rows) != 1:
print("your username is bad or duplicate")
or
rows = cur.fetchall()
if cur.rowcount != 1:
print("your username is bad or duplicate")
Related
I've been trying to learn how to use sqlite3 for python 3.10 and I can't find any explanation of how I'm supposed to grab saved data From a database and insert it into a variable.
I'm attempting to do that myself in this code but It just prints out
<sqlite3.Cursor object at 0x0000018E3C017AC0>
Anyone know the solution to this?
My code is below
import sqlite3
con = sqlite3.connect('main.db')
cur = con.cursor()
#Create a table called "Datatable" if it does not exist
cur.execute('''CREATE TABLE IF NOT EXISTS datatable
(Name PRIMARY KEY, age, pronouns) ''')
# The key "PRIMARY KEY" after Name disallow's information to be inserted
# Into the table twice in a row.
name = 'TestName'#input("What is your name? : ")
age = 'TestAge'#input("What is your age? : ")
def data_entry():
cur.execute("INSERT INTO datatable (name, age)")
con.commit
name = cur.execute('select name from datatable')
print(name)
Expected result from Print(name) : TestName
Actual result : <sqlite3.Cursor object at 0x00000256A58B7AC0>
The execute statement fills the cur object with data, but then you need to get the data out:
rows = cur.fetchall()
for row in rows:
print(row)
You can read more here: https://www.sqlitetutorial.net/sqlite-python/sqlite-python-select/
How Normal Create Works in a Database
In most create circumstances, you don't want to create a new node if one of the unique or primary keys already exist in the database. I also don't want to update the node, as that would be an upsert. I want to do nothing if the key exists in the database. This will work just like a unique constraint.
Create with a Unique Key
If I want only the email field to be unique, I can do this:
MERGE (u:User { email: 'me#you.com' })
ON CREATE SET u.name='Jon Smith'
RETURN u
It won't create the user if there is already an email.
Create with Multiple Unique Keys ?
Let's say I don't want the user to be able to create a user where a username or email is already in the database. You would think this would work:
MERGE (u:User { email: 'me#you.com', username: 'bill' })
ON CREATE SET u.name='Jon Smith'
RETURN u
However, this will still create the node, as only the COMBINATION has to be unique. I want both values separately to be unique... or fail.
Conditional Create
What I want is a conditional create: IF X THEN Y where:
x = email OR username IS NOT IN User
y = CREATE User email="me#you.com", username="bill", role="admin", ...
How can this be done?
J
Please consider the following query:
GRAPH.QUERY g "cypher email='a' username='b'
OPTIONAL MATCH (n)
WHERE n.email = $email OR n.username = $username
WITH n is null as missing
WHERE missing = true
CREATE ({email:$email, username:$username})"
Given an empty graph:
GRAPH.QUERY g "cypher email='a' username='b' OPTIONAL MATCH (n) WHERE n.email = $email OR n.username = $username WITH n is null as missing WHERE missing = true CREATE (n {email:$email, username:$username})"
1) 1) "Nodes created: 1"
2) "Properties set: 2"
3) "Cached execution: 0"
4) "Query internal execution time: 1.469000 milliseconds"
GRAPH.QUERY g "cypher email='a' username='b' OPTIONAL MATCH (n) WHERE n.email = $email OR n.username = $username WITH n is null as missing WHERE missing = true CREATE (n {email:$email, username:$username})"
1) 1) "Cached execution: 1"
2) "Query internal execution time: 0.614000 milliseconds"
Running the exact same query twice, the first execution created the missing node the second one didn't modified the graph.
To start off, I really don't know if this have been answered before.
I looked all over but still couldn't find an example..
And I'm new to SQLite3 and obviously I would run into these kind of problems.
Basically what I'm doing is creating a SQLite3 database save as : "Data.dll".
And I've created a table and inserted some data in there..
Now, basically what I want to do is like ask the user a question, and the user has to input a number AND a "Key".
When inputted I want to check if it's valid.
For example,
DATA #1 :
NUMBERID : 30138
KEY: KeyUser1
DATA #2 :
NUMBERID : 1144
KEY : key2
If those were both inputted (Like 30138, and KeyUser1. not like 30138 and key2) then they can keep going, otherwise, It would say that the NUMBER ID and "KEY" Do not match.
So how can I do that?
I'm new to SQLite3 and so I'm still a newbie...
Any help is appreciated.
My Code:
import sqlite3
dbase = sqlite3.connect("Data.dll")
print "DataBase Opened : Success."
dbase.execute(""" CREATE TABLE IF NOT EXISTS Keys(
NUMBERID INT PRIMARY KEY NOT NULL,
VAILD TEXT NOT NULL)""")
print "DataBase Table : Success"
def insert_record(NUMBERID,VAILD):
dbase.execute(""" INSERT INTO Keys (NUMBERID,VAILD)
VALUES(?,?)""", (NUMBERID,VAILD))
dbase.commit()
#insert_record(1144, 'key2') # If needed to insert soemthing...
print "DataBase Insert : Success."
def read_Data():
data = dbase.execute(""" SELECT NUMBERID,VAILD FROM Keys """)
for record in data:
NUMBER_ID = str(record[0])
VAILD_KEY = str (record [1])
print NUMBER_ID # Check
print VAILD_KEY # Check
read_Data()
NUMBER_ENTER = input ("Enter NUMBER ID : ")
VAILD_ENTER = raw_input ("Enter KEY : ")
if NUMBER_ENTER in NUMBER_ID:
print "1" # If its at least correct print this
...
else:
print "2" # wrong
...
if VAILD_ENTER in VAILD_KEY:
print "a" # if its at least correct , print this.
...
else:
print "z" # wrong
...
dbase.close()
print "DataBase Closed : Success."
you could try this:
def check(number, key):
data = dbase.execute("select 1 from keys where NUMBERID = ? AND VAILD = ?", (number, key)).fetchone()
return data
NUMBER_ENTER = input("Enter NUMBER ID : ")
VAILD_ENTER = raw_input("Enter KEY : ")
if check(NUMBER_ENTER, VAILD_ENTER):
print 1
else:
print 2
where you check if there is a row with the NUMBERID, VAILD
Out of my depth here.
Have an assignment to download data from web and get it into SQL lite.
have pieced together some different code.
the key code is below. Suggestions on fixing how to get the data into the SQL table appreciated.
The API code works fine, It downloads a header row, and rows containing a country name and visitor numbers from that country. so its the SQL that i'm trying to write thats failing. No errors, just no data going in.
return service.data().ga().get(
ids='ga:' + profile_id,
start_date='2016-04-01',
end_date='today',
metrics='ga:users',
dimensions='ga:country').execute()
def print_results(results):
print()
print('Profile Name: %s' %results.get('profileInfo').get('profileName'))
print()
Print header.
output = []
for header in results.get('columnHeaders'):output.append('%30s' % header.get('name'))
print(''.join(output))
Print data table.
start databasing results
if results.get('rows', []):
for row in results.get('rows'):
output = []
for cell in row:output.append('%30s' % cell)
cur.execute('SELECT max(id) FROM Orign')
try:
row = cur.fetchone()
if row[0] is not None:start = row[0]
except:
start = 0
row = None
cur.execute('''INSERT OR IGNORE INTO Origin (id, Country, Users)
VALUES ( ?, ?, )''', ( Country, Users))
conn.commit()
cur.close()
print(''.join(output))
start = 0
else:
print('No Rows Found')
if __name__ == '__main__':
main(sys.argv)
I am attempting to create a table to serve as a small database for users:
users = {}
function create_new_user()
print("Enter a unique user name (up to 12 letters): ")
local name = io.read()
if #name > 12 then
print ("That name is too long.")
return create_new_user()
elseif users[name] then
print ("That name is already in use.")
return create_new_user()
else
table.insert(users, 1, name)
print("Your new user name is: ", users[name])
end
end
I understood from the manual that the line
table.insert(users, 1, name)
would insert the string value of name as an element of the users array. This is not the case-- whenever I run the script I get the following output:
Your new user name is: nil
You insert the element into the table, but you are trying to retrieve the value indexed by the value of name, which is not what you stored (you are using users[name] instead of users[1]). You can probably do something like this:
table.insert(users, name)
print("Your new user name is: ", name)
Note that table.insert(users, 1, name) may not do what you expect as this will prepend elements to the table. If you insert "abc" and "def" this way, then the users table will include elements {"def", "abc"} (in this particular order). To retrieve the last inserted element you can use users[1].
If you want to store values in a different order, you need to use table.insert(users, name), which will append elements to the table. To retrieve the last element you can use users[#users].
If you always want to store the added element in the first position in the table, then you can simply use users[1] = name.
Here you index the user table with a string (the name):
elseif users[name] then
You do the same here:
print("Your new user name is: ", users[name])
But you store the name with a numerical index:
table.insert(users, 1, name)
What you want instead of that line is:
users[name] = name
Or this (which would require changing the line that follows):
users[name] = true
The idea is you're only really using the keys, to create a lookup table.