Reading data from SQLite3 database and using them - database

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

Related

I am struggling to select a string of data from a database table and print it as a variable

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/

sqlite3 selecting values based on python variables

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

Creating multiple rows in databases

I'm not sure why I can't test my function. My desired output is ID, then Room, but if there are multiple rooms for the same ID, then put it in a new row, like
ID Room
1 SW128 SW 143
into
ID Room
1 SW128
1 SW143
This is some of the data in the file.
1,SW128,SW143
2,SW309
3,AA205
4,AA112,SY110
5,AC223
6,AA112,AA206
but I can't even test my function. Can anyone please help me fix this?
def create_location_table(db, loc_file):
'''Location table has format ID, Room'''
con = sqlite3.connect(db)
cur = con. cursor()
cur.execute('''DROP TABLE IF EXISTS Locations''')
# create the table
cur.execute('''CREATE TABLE Locations (id TEXT, Room TEXT)''')
# Add the rows
loc_file = open('locations.csv', 'r')
loc_file.readline()
for line in loc_file:
d = {}
data = line.split(',')
ID = data[0]
Room = data[1:]
for (ID, Room) in d.items():
if Room not in d:
d[ID] = [Room]
for i in Rooms:
cur.execute(''' INSERT INTO Locations VALUES(?, ?)''', (ID,
Room))
# commit and close cursor and connection
con.commit()
cur.close()
con.close()
The problem is, that d is always an empty dict, so the for (ID, Room) in d.items() won't do anything. What you need to do is looping over Room. And you don't need the d dict.
def create_location_table(db, loc_file):
'''Location table has format ID, Room'''
con = sqlite3.connect(db)
cur = con. cursor()
cur.execute('''DROP TABLE IF EXISTS Locations''')
# create the table
cur.execute('''CREATE TABLE Locations (id TEXT, Room TEXT)''')
# open the CSV
csv_content = open(loc_file, 'r')
for line in csv_content:
data = line.strip().split(',')
# made lowercase following PEP8, but 'id' is a built in name in python
idx = data[0]
rooms = data[1:]
# loop through the rooms of this line and insert one row per room
for room in rooms:
cur.execute(''' INSERT INTO Locations VALUES(?, ?)''', (idx, room))
# for debug purposes only
print('INSERT INTO Locations VALUES(%s, %s)' % (idx, room))
# commit and close cursor and connection
con.commit()
cur.close()
con.close()
# call the method
create_location_table('db.sqlite3', 'locations.csv')
Note: Following PEP 8 I made your variables lowercase.
EDIT: post full code example, use loc_file parameter

Ruby printing out hash data

I am working on a database that holds records for a school, where the key is the studentID, followed by the values of, first name, last name, major, and catalog year. I am working on the display function, which loops through the users which have been added to the hash. however, my code is not printing out of all the records i have added to the database.
it is only printing out one record listing, rather than my multiple inputted entries.
here is an example of input:
-----------------------------
Student Database Records
-----------------------------
1) Insert new record to database
2) Modify record in database
3) Remove record from database
4) Display record(s) in database
5) Quit
6) Enter choice:
1
-----------------------------
Add Record(s)
-----------------------------
Enter Student Identifcation Number:
32424
Enter First name of Student:
sfsdf
Enter Last name of Student:
sdfsfsf
Enter Major of Student:
sdfsdfs
Enter Catalogue Year:
sdfsfds
Your entry for Student ID 32424 has been added to the database.
------------------------------------------------------------------------
32424: sfsdf, sdfsfsf, sdfsdfs, sdfsfds
------------------------------------------------------------------------
here is my code to add an array to a hash
student_id = gets().chomp
if school_database.sDB.has_key?(student_id)
puts "Student Record Already Existent"
return school_database
end
puts "\nEnter First name of Student: "
first_name = gets().chomp
puts "\nEnter Last name of Student: "
last_name = gets().chomp
puts "\nEnter Major of Student: "
major = gets().chomp
puts "\nEnter Catalogue Year: "
catalogue_year = gets().chomp
puts "\nYour entry for Student ID #{student_id} has been added to the database.\n"
puts "\n------------------------------------------------------------------------"
puts "#{student_id}: #{first_name}, #{last_name}, #{major}, #{catalogue_year}"
puts "------------------------------------------------------------------------\n\n"
store_account_data = first_name + "," + last_name + "," + major + "," + catalogue_year
school_database.sDB[student_id] = [store_account_data]
return school_database
here is the code i am using to loop through my hash to print out the records.
school_database.sDB.each do |key, store_account_data|
puts "\n"
puts "#{key}: #{store_account_data.join(',')}"
positively, I run the .size command, and i discovered that it is adding muliple entries to the hash, however, it is not printing all of them
any ideas?
String’s + method places fairly strict requirements on what can appear on the right-hand side. You need to explicitly call to_s:
puts key + ' : ' + store_account_data.to_s
String interpolation is much more forgiving; it basically calls to_s for you:
puts "#{key} : #{store_account_data}"
Or perhaps you want a more detailed dump:
puts "#{key} : #{store_account_data.inspect}"
Or no brackets:
puts "#{key} : #{store_account_data.join(', ')}"
Or perhaps elements of store_account_data are objects, and you want to just print one property of them:
puts "#{key} : #{store_account_data.map(&:field_to_print).join(', '}"
I would do something like:
def display(database)
database.sDB.each do |key, account|
puts "#{key}: #{account.join(',')}"
end
end
You can use ruby's join method. I believe that's pretty common among languages.

Trouble adding elements to a table (array in Lua)

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.

Resources