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")
Related
I have checked other codes and solutions but I just cant come to find the solution.
CODE
table = "create table salesperson (code int, name varchar(35), salary int, itcode varchar(4))"
cursor.execute(table)
code = int(input('Enter the code:'))
name = input('Enter the name:')
salary = int(input('Enter the salary:'))
itcode = input('Enter the itcode:')
command = "insert into account(code,name,salary,itcode) values(%s,%s,%s,%s)"
values = (code, name, salary, itcode)
cursor.execute(command, values)
mycon.commit()
print('record(s) inserted')
ERROR
I suggest you separate the creation of table entities into its own function. Then use MySQL Workbench or another tool to verify that your schema is being created correctly.
Looks like you are creating one table salesperson but inserting into account? Check that out.
I have created a table to store information and data for each user in a simple social media website. I have the column "friends" and I want this column to have multiple values seperated by a comma. for example, "John, Maria, Batman etc...". Shortly, each time the user clicks at the Follow Button, the name of the another person is being added to the column "friends".
with sqlite3.connect('memory.db') as conn:
cursor = conn.cursor()
cursor.execute(
"CREATE TABLE users (user_id char(50), name char(50), email char(50), password char(30), "
"university char(50), birthday char(50), age char(10), hometown char(50), photo, status char(50), friends char(1000));")
name = session['name'] #the name of the user
name_search = session['name_search'] #the name of the person who we want to follow
if name != name_search:
cursor.execute('''UPDATE users SET friends=? WHERE name=?''', (name_search, name))
conn.commit()
I've used the method UPDATE but it updates the column only with the one value...
If I have 3 tables
table called students (student_id,student_name)
students data: (1, john),(2, Mike),(3, Adam)
table called courses (course_id,course_name)
courses data: (1,math),(2,english),(3,science)
table called Enrollment (student_id,course_id)
enrollment data: (1,1),(1,2),(1,3),.....student cannot enroll twice in same course like (1,1),(1,1)
CREATE TABLE "enrollment" (
"student_id" INTEGER,
"course_id" INTEGER,
FOREIGN KEY("student_id") REFERENCES "students"("student_id"),
PRIMARY KEY("student_id","course_id"),
FOREIGN KEY("course_id") REFERENCES "courses"("course_id")
);
To enroll in a course:
I want to let the user enter student_id and based on student_id user enroll
When user enter course_id
my code:
def enroll(student_id,course_id):
dbase.execute(''' INSERT INTO enrollment(student_id,course_id)
VALUES(?,?)''',(student_id,course_id))
dbase.commit()
print("Record inserted")
student_id = int(input('Enter student id: ')
data = cur.execute("SELECT * FROM students WHERE student_id= ?",(student_id,))
found = data.fetchone()
if found:
course_id = int(input("Enter the course id: "))
if course_id >= 1 and course_id <= 3:
enroll(student_id,course_id)
else:
print('please try with valid course id!')
main_menu()
else:
main_menu()
student can't enroll twice in same course
How can I fix this code?
I am using python/SQLite
You don't need to create a separate enrollment table for setting course_id for a student, just add course_id field to students table. But if you need a separate table, just add a unique constraint on student_id field, add the following line to create table enrollment script, or alter that table
CONSTRAINT uc_student_id UNIQUE (student_id)
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.
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, ))