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