Get an automatic ID in the Python shell with SQlite - python

I need assistance with creating an automatic ID for the Employee's when the other information is inputted by the user, is anyone able to help? I don't want the Employee ID to be asked to be inputted by the user, I would like it to be automatically generated and inputted into that field. I also have to program it in python, I can't use a SQL program or anything. Feel free to change any parts of the code, it's pretty flimsy at the moment, I've been messing around with the 'rowid' code for a bit trying to get that to work and I can't figure it out, many thanks.
import sqlite3
def AddEmployee():
FirstName = input("Plaese enter the
employee's First Name: ")
LastName = input("Please enter the
employee's Last Name: ")
DName = input("Please Enter the employee's
Department Area: ")
Gender = input("Please enter the employee's
Gender: ")
Phone = int(input("Please enter the
employee's phone number: "))
Address1 = input("Please Enter the
employee's Address1: ")
Town = input("Please Enter the employee's
Town: ")
Postcode = input("Please Enter the
employee's Postcode: ")
DOB = input("Please Enter the employee's
Date of Birth: ")
HireDate = input("Please Enter the
employee's Date of Employment: ")
db = sqlite3.connect("Database.db")
cursor = db.cursor()
cursor.execute("INSERT INTO Employees
VALUES(rowid, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(EmployeeID, FirstName, LastName, DName,
Gender, Phone, Address1, Town, Postcode,
DOB, HireDate))
db.commit()
cursor.close()
db = sqlite3.connect("Database.db")
cursor = db.cursor()
cursor.execute("""CREATE TABLE IF NOT
EXISTS Employees
(EmployeeID integer PRIMARY KEY
AUTOINCREMENT, DName integer,
FirstName text, LastName text, Gender text,
Phone text,
Address1 text, Town text, Postcode text,
DOB Date,
HireDate Date)""")
cursor.execute("""CREATE TABLE IF NOT
EXISTS Salaries
(SalaryID integer PRIMARY KEY
AUTOINCREMENT, EmployeeID integer,
DepartmentDI integer, RegisterID integer,
FirstName text,
LastName text, Address1 text, Town text,
Postcode text, DOB Date,
HireDate Date, SalaryAmount integer,
DhourlyRate integer,
DOvertimeHourlyRate integer)""")
cursor.execute("""CREATE TABLE IF NOT
EXISTS Register
(RegisterID integer PRIMARY KEY
AUTOINCREMENT, EmployeeID integer,
Date Date, Time Time, Present Boolean,
HoursWorked integer,
OvertimeWorked integer)""")
cursor.execute("""CREATE TABLE IF NOT
EXISTS Departments
(DepartmentID integer PRIMARY KEY
AUTOINCREMENT, DName text, DQuota integer,
DHourlyRate integer, DovertimeHourlyRate
integer)""")
db.commit()
cursor.close()
AddEmployee()

you can do this
id = odm.SymbolField(primary_key=True)
If you dont have a field with a Primary Key than python create it automaticly.

Related

Python-sqlite3 : How to put a python variable in SELECT statement

How can I put a python variable just after the SELECT. The idea is to create a python function with three arguments where you can choose what you what (here, it's the age) from whom (here, it's Mike and James)
conn = sqlite3.connect('test.s3db')
cur = conn.cursor()
cur.execute('''DROP TABLE IF EXISTS people''')
cur.execute('''CREATE TABLE IF NOT EXISTS people
(id INTEGER,
name TEXT,
surname TEXT,
age INTEGER,
alone INTEGER DEFAULT 0);''')
def add_people(id, name, surname, age, alone=0):
cur.executemany('INSERT INTO people (id, name, surname, age, alone) VALUES (?,?,?,?,?)', [(id, name, surname, age, alone)])
conn.commit()
add_people(1, 'SMITH','James',45)
add_people(2,'JOHNSON','Mike',75)
cur.execute('''SELECT (?) FROM people WHERE surname = (?) OR surname = (?)''', ('age','Mike', 'James'))
print(cur.fetchall())
My code return:
[('age',), ('age',)]
instead of :
[(75,), (45,)]
EDIT : I want that what is selected is a variable and not directly written in the query. My goal is to make a function like this one :
def query(what, who_1, who_2):
cur.executemany('''SELECT (?) FROM people WHERE surname = (?) OR surname = (?)''', (what, who_1, who_2))
return cur.fetchall()
Thank you in advance for your answers !
This takes the data you need as argument of select_data_of
import sqlite3
def add_people(id, name, surname, age, alone=0):
cur.executemany('INSERT INTO people (id, name, surname, age, alone) VALUES (?,?,?,?,?)', [(id, name, surname, age, alone)])
conn.commit()
def select_data_of(names, data="age"):
select = []
for name in names:
cur.execute(f'''SELECT [{data}] FROM people WHERE surname = (?)''', (name, ))
select.append(cur.fetchall()[0])
return select
with sqlite3.connect('test.s3db') as conn:
cur = conn.cursor()
cur.execute('''DROP TABLE IF EXISTS people''')
cur.execute('''CREATE TABLE IF NOT EXISTS people
(id INTEGER,
name TEXT,
surname TEXT,
age INTEGER,
alone INTEGER DEFAULT 0);''')
add_people(2,'JOHNSON','Mike',75)
add_people(1, 'SMITH','James',45)
data = select_data_of(("Mike", "James"), data="age")
print(data)
OUT:
[(75,), (45,)]
I think your select query is wrong because of the 'ages' parameter, this new query will work.
Try
cur.execute("SELECT [age] FROM people WHERE surname = 'Mike' OR surname = 'James")

How to break a while loop when break is supposed to be used in defining a function?

u=input('enter your sql password ')
import mysql.connector as s
mycon=s.connect(host='localhost',user='root',passwd='{}'.format(u))
cursor=mycon.cursor()
cursor.execute('create database if not exists Reservation')
cursor.execute('use reservation')
cursor.execute("create table if not exists USER(user_id int primary key, first_name varchar(100), last_name varchar(100), aadhar_no varchar(50), gender varchar(10), age int, mobile_no varchar(50), email varchar(100), city varchar(100), state varchar(100), pincode varchar(50), password varchar(100))")
cursor.execute("create table if not exists TRAIN(train_no int primary key, train_name varchar(100), arrival_time time, departure_time time, availability_of_seats varchar(50), date date)")
cursor.execute("insert into TRAIN values(11019, 'Konark Express', '153000','154000','A','2020-04-10')")
cursor.execute("insert into TRAIN values(12025, 'Shatabdi Express','050000','055000','A','2020-04-10')")
cursor.execute("insert into TRAIN values(22881, 'Pune Express','114000','115000','A','2020-04-10')")
cursor.execute("insert into TRAIN values(10101, 'Mandovi Express','130000','133000','A','2020-04-10')")
cursor.execute("insert into TRAIN values(18520, 'LTT Express','071000','073000','A','2020-04-10')")
cursor.execute("create table if not exists STATION(station_no int, name varchar(100), hault int, arrival_time varchar(6), train_no int, primary key(station_no, train_no), constraint foreign key(train_no) references TRAIN(train_no))")
cursor.execute("insert into STATION values(1,'Kalyan',10,'140000',11019)")
cursor.execute("insert into STATION values(2,'Secunderabad',25,'142500',12025)")
cursor.execute("insert into STATION values(3,'Hyderabad',10,'210000',22881)")
cursor.execute("insert into STATION values(4,'Panvel',15,'132500',10101)")
cursor.execute("insert into STATION values(5,'Thane',10,'074000',18520)")
cursor.execute("create table if not exists STARTS(train_no int primary key , station_no int)")
cursor.execute("insert into STARTS values(11019,1)")
cursor.execute("insert into STARTS values(12025,2)")
cursor.execute("insert into STARTS values(22881,3)")
cursor.execute("insert into STARTS values(10101,4)")
cursor.execute("insert into STARTS values(18520,5)")
cursor.execute("create table if not exists REACHES(train_no int, station_no int, time time)")
cursor.execute("insert into REACHES values(11019,5,'140000')")
cursor.execute("insert into REACHES values(12025,3,'142500')")
cursor.execute("insert into REACHES values(22881,4,'210000')")
cursor.execute("insert into REACHES values(10101,2,'132500')")
cursor.execute("insert into REACHES values(18520,1,'074000')")
mycon.commit()
z=1
while True:
import tkinter as t
root=t.Tk()
root.title('railway tickect booking system')
e=t.Entry(root,width=35)
e.grid(row=0,column=0)
e.insert(0,'enter your user id')
f=t.Entry(root,width=35)
f.grid(row=1,column=0)
f.insert(0,'enter your first name')
g=t.Entry(root,width=35)
g.grid(row=2,column=0)
g.insert(0,'enter your last name')
h=t.Entry(root,width=35)
h.grid(row=3,column=0)
h.insert(0,'enter your adhar card no. ')
i=t.Entry(root,width=35)
i.grid(row=4,column=0)
i.insert(0,'gender')
j=t.Entry(root,width=35)
j.grid(row=5,column=0)
j.insert(0,'age')
k=t.Entry(root,width=35)
k.grid(row=6,column=0)
k.insert(0,'your mobile number')
l=t.Entry(root,width=35)
l.grid(row=7,column=0)
l.insert(0,'email')
m=t.Entry(root,width=35)
m.grid(row=8,column=0)
m.insert(0,'enter your city')
n=t.Entry(root,width=35)
n.grid(row=9,column=0)
n.insert(0,'enter your state')
o=t.Entry(root,width=35)
o.grid(row=10,column=0)
o.insert(0,'enter your pincode')
p=t.Entry(root,width=35)
p.grid(row=11,column=0)
p.insert(0,'enter your password')
t.Label(root,text='which train would you travel in?').grid(row=14,column=0)
r=t.IntVar()
t.Radiobutton(root,text='Konark Express-Kalyan to Thane',variable=r,value=11019).grid(row=15,column=0)
t.Radiobutton(root,text='Shatabdi Express-Secunderabad to Hyderabad',variable=r,value=12025).grid(row=16,column=0)
t.Radiobutton(root,text='Pune Express-Hyderabad to Panvel',variable=r,value=22881).grid(row=17,column=0)
t.Radiobutton(root,text='Mandovi Express-Panvel to Secunderabad',variable=r,value=10101).grid(row=18,column=0)
t.Radiobutton(root,text='LTT Express-Thane to Kalyan',variable=r,value=18520).grid(row=19,column=0)
def click1():
mycon=s.connect(host='localhost',user='root',passwd='{}'.format(u),database='reservation')
cursor=mycon.cursor()
cursor.execute("create table if not exists TICKET(id int primary key default {}, user_id int, train_no int)".format(z))
cursor.execute("insert into user values({},'{}','{}','{}','{}',{},'{}','{}','{}','{}','{}','{}')".format(int(e.get()),f.get(),g.get(),h.get(),i.get(),int(j.get()),k.get(),l.get(),m.get(),n.get(),o.get(),p.get()))
cursor.execute("insert into TICKET(user_id,train_no) values({},{})".format(int(e.get()),r.get()))
top=t.Toplevel()
top.title('ticket preview')
t.Label(top,text='userid').grid(row=0,column=0)
t.Label(top,text='ticket id').grid(row=0,column=1)
t.Label(top,text='first name').grid(row=0,column=2)
t.Label(top,text='surname').grid(row=0,column=3)
t.Label(top,text='train').grid(row=0,column=4)
t.Label(top,text='arrival time').grid(row=0,column=5)
t.Label(top,text='{}'.format(e.get())).grid(row=1,column=0)
t.Label(top,text='{}'.format(z)).grid(row=1,column=1)
t.Label(top,text='{}'.format(f.get())).grid(row=1,column=2)
t.Label(top,text='{}'.format(g.get())).grid(row=1,column=3)
cursor.execute("select train_name from TRAIN where train_no={}".format(r.get()))
t.Label(top,text='{}'.format(cursor.fetchone())).grid(row=1,column=4)
cursor.execute("select arrival_time from STATION where train_no={}".format(r.get()))
t.Label(top,text='{}'.format(cursor.fetchone())).grid(row=1,column=5)
mycon.commit()
mybutton=t.Button(root,text='submit and proceed',command=click1)
mybutton.grid(row=20,column=0)
top=t.Toplevel()
t.Label(top,text='would you like to enter more records?').grid(row=2,column=0)
x=t.IntVar()
t.Radiobutton(top,text='yes',variable=x,value=1).grid(row=3,column=0)
t.Radiobutton(top,text='no',variable=x,value=0).grid(row=4,column=0)
def click2():
if x.get()==0:
t.Label(top,text='close the windows').grid(row=6,column=0)
break
elif x.get()==1:
t.Label(top,text='close all the windows to enter new record').grid(row=6,column=0)
t.Button(top,text='submit',command=click2).grid(row=5,column=0)
z+=1
root.mainloop()
The program is showing error saying that the break statement is out of loop.
My main objective was to receive entries from user and add it to my sql database reservation.
so to add more records I created a while loop.
if the user wants to continue writing more records the loop will go on or else it will break.
but I don't know how to proceed since its showing error.

Getting a NamError when using Python and SQL

I'm running a student database and using python 2.7 on pycharm. Here is the script
FirstName = input("Enter the Student's first name")
if not FirstName or type(FirstName) != str:
print("Enter a real name silly")
exit()
and the create Table stement looks like so
drop table if exists StudentID;
drop table if exists FirstName;
drop table if exists LastName;
drop table if exists GPA;
drop table if exists Major;
drop table if exists FacultyAdvisor;
CREATE TABLE Student(
StudentID int PRIMARY KEY AUTOINCREMENT ,
FirstName varchar(25),
LastName varchar(25),
GPA NUMERIC,
Major varchar(10),
FacultyAdvisor varchar(25)
)
and the error I'm getting is
FirstName = input("Enter the Student's first name")
File "<string>", line 1, in <module>
NameError: name 'john' is not defined
My guess is that you're using Python2
You need to use the raw_input() method when receiving String input from the user:
FirstName = raw_input("Enter the Student's first name")

SQLite3: Python Input to Table - Trouble with Auto Increment

I am currently having an issue with importing data to a sqlite3 table.
In my TEST program, users input their fake information when asked for an input.
I then take that input and put it in my Table, however, I am having an issue with the AutoIncrementing "User ID". Each user gets their own ID, and so far there are 5 users. When a new User inputs their data, how do I make it so it automatically sets "UserID" to the next number, in this case 6.
Everything works if I manually put "6" in the first Value (in the following code), but how do I make that automatic?
conn = sqlite3.connect('xxxxxxx.db')
c=conn.cursor()
NameCreate = input("Please enter your First and Last name: ")
UserNameCreate = input("Please enter your desired User Name: ")
PasswordCreate = input("Please enter your desired Password: ")
DOBCreate = input("Please enter your date of birth [DD.MM.YYYY]: ")
FavouriteArtistCreate = input("Please enter your favourite Arist: ")
FavouriteGenreCreate = input("Please enter your favourite Genre: ")
c.execute("INSERT INTO Users VALUES (AUTOINCREMENT, '{0}', '{1}', '{2}', '{3}', '{4}', '{5}')".format(NameCreate, DOBCreate, UserNameCreate, PasswordCreate, FavouriteArtistCreate, FavouriteGenreCreate))
conn.commit()
It's not enough to show your operations on the database. You need to show your database schema.
We start with two pieces of warning from sqlite doc:
The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed.
In SQLite, a column with type INTEGER PRIMARY KEY is an alias for the ROWID (except in WITHOUT ROWID tables) which is always a 64-bit signed integer.
With that out of the way, the problem with your code is that autoincrement is specified at table creation time, not insertion time.
See a minimal example:
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
NameCreate = 'a'
c.execute("INSERT INTO users ('name') VALUES (?)", (NameCreate, ))
conn.commit()
print(c.execute('select * from users').fetchall())
NameCreate = 'b'
c.execute("INSERT INTO users ('name') VALUES (?)", (NameCreate, ))
conn.commit()
print(c.execute('select * from users').fetchall())
note the CREATE TABLE line with AUTOINCREMENT, although it's not necessary as sqlite3 will do AUTOINCREMENT on any INTEGER PRIMARY KEY.
So you will need to migrate your database to a new schema with that in your table.
A bad manual solution without migration can go as follows (only for stopgap!), in the above example:
c.execute("INSERT INTO users ('id', 'name') VALUES ((SELECT MAX(id) + 1 FROM users), ?)", (NameCreate, ))

Primary Key issues when using raw_input with SQLite 3 and Python

in my database I'm using raw_input to allow users to enter data into a database, the problem is that I have an ID assigned to each record of data that is the primary key of the table.
username = raw_input("What would you like your username to be? ")
email = raw_input("What is your email address? ")
firstName = raw_input("What is your first name? ")
surname = raw_input("What is your surname? ")
age = raw_input("How old are you? ")
password = raw_input("What is your password?") #Encryption method will be added later
age = int(age) #Changing the age variable into an integer so it can be inputted into the database
#DB part
conn = db.connect('apollo.db') #Connecting to the database
cursor = conn.cursor()
cursor.execute("INSERT INTO users VALUES(?, ?, ?, ?, ?, ?)",
(username, email, firstName, surname, age, password)) #Inserting the user's data into the table
conn.commit() #Committing the changes
conn.close() #Closing the connection
I assumed that because the primary key increments automatically that it would not be needed to be added into the code because each record would automatically get a number. The problem is, I get this error message when I've answered all of the raw_input questions:
sqlite3.OperationalError: table users has 7 columns but 6 values were supplied
Is there something I need to add to the code for the primary key?
I guess the problem is this:
cursor.execute("INSERT INTO users VALUES(?, ?, ?, ?, ?, ?)",
Try this exchange of that:
cursor.execute("INSERT INTO users (username, email, firstName, surname, age, password) VALUES ",
(username, email, firstName, surname, age, password))
and i think this link can explain it more for you my friend.

Categories

Resources