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")
I have two tables created from below query in SQLite:
CREATE TABLE people (
id integer unique primary key,
first_name text,
middle_name text,
last_name text,
email text,
phone text
);
CREATE TABLE companies (
id integer unique primary key,
name text,
url text,
contact integer,
FOREIGN KEY(contact) REFERENCES people(id)
);
I have all the data available in the first table, but I want to popup id in second table same as id in the first table.name in the companies table is concatenated string of first_name text,middle_name,last_name in people table.
I want something like "UPDATE companies SET contact = (SELECT people.id FROM people WHERE companies.name = people.first_name || "," || "people.second_name"; it will be great if I can show the string in people table is the subset of string in companies table
I am a beginner in python and SQlite both.
I have been working on this function in python. I intend for it to iterate over a list of phone numbers, checking with a database to see whether the number has been used yet or not. If it has been used, it should remove the phone number from the list and choose another and check the new one until an unused one has been found and return the unused one. If it has not been used, it should simply just return the number. However, after one run, it picks a number, checks it, runs, and then enters it into the database. The next run deletes the previously used number, and picks another that hasn't been used. It continues to run and enters this number into the database. The third run does not delete the previously used number from the list, but it still picks a new one regardless. Although this still works, when the numbers run out, since there are no others to pick, it continues using the last number in the list for every following run of the script. Sorry if the code is a bit sloppy right now, I am in a bit of a rush and this is only a script I have been messing around with. I hope this is clear, and not too confusing. If I need to clear any confusion, I will be glad too.
Edit: Sorry, I forgot to mention that these phone numbers are constantly grabbed from a website by another script. These set of numbers listed below is just a dummy set for testing. So in the end, I am needing to see if these recently grabbed numbers have been used by checking with the database tables.
import random
import names
##############################Information Variables##################################
emailAddress = "Fakeemail#mail.com"
titleValues = [0,1] #0 is 'Mr.', 1 is 'Mrs.'
country = 'Schwifty'
title = random.choice(titleValues)
#Generate a random name based on gender
if title == 1:
firstName = names.get_first_name(gender= 'female')
else:
firstName = names.get_first_name(gender= 'male')
lastName = names.get_last_name()
fullName = firstName + ' ' + lastName
print(fullName)
phoneNumber = '111-222-3333'
#########################################################
import sqlite3
import time
import datetime
conn = sqlite3.connect('accounts.db')
c = conn.cursor()
def createTable():
c.execute('CREATE TABLE IF NOT EXISTS accounts(Email TEXT, Name TEXT, Title TEXT, PhoneNumber TEXT, Country TEXT, DateStamp TEXT)')
def dynamic_data_entry(email, name, title, phone, country):
unix = time.time()
date = str(datetime.datetime.fromtimestamp (unix).strftime('%Y-%m-%d %H:%M:%S'))
c.execute('INSERT INTO accounts (Email, Name, Title, PhoneNumber, Country, DateStamp) VALUES (?, ?, ?, ?, ?, ?)', (email, name, title, phone, country, date))
conn.commit()
createTable()
#################################TEST NUMBER CHECK###########################
phoneNumbers = ['111-222-3333', '444-555-6666', '777-888-9999', '123-456-7890', '321-321-321']
def checkNumber(a):
c.execute("SELECT * FROM accounts WHERE PhoneNumber = ?", (a,))
row = c.fetchall()
if row:
print("Phone number has already been used, choosing another and deleting current from list.")
phoneNumbers.remove(a)
a = random.choice(phoneNumbers)
checkNumber(a)
elif row == False:
print("Number is fresh and new, using " + a)
return a
elif row == None:
print('No new phone numbers to use, exiting... ')
exit()
# for num in phoneNumbers:
# checkNumber(num)
# print(num)
checkNumber(phoneNumber)
print(phoneNumbers)
print('working')
##########################################
# INSERT DATA TO DB #
##########################################
#Insert information to database in this order: email, name, title, phone, country
dynamic_data_entry(emailAddress, fullName, title, phoneNumber, country)
conn.commit()
c.close()
conn.close()
Don’t do this. Populate a table with your phone numbers and update each phone number record with a field like ‘used’ once used.
Always keep state and data modeling in the database where possible. It is made for it.
Update in response to OP:
Create a separate table for phone numbers and replace your number field in the accounts table with a foreign key id to the primary key of the phone number table. This is called maintaining an object model or data model, so that if you want to query accounts, you have the data you need via foreign key, and if you just want phone numbers you can query the phone numbers table directly.
This way your phone number ‘objects’ can have their own attributes like ‘already called’ or ‘on do not call list’ without muddying up your accounts ‘object’.
If you want to insert a new account, you should first insert your new phone number 'object' into the phone number table and return the id, and then use that in your account insert.
I am trying to query whether the staff ID and password are correct. The query works, however I want to get the fname and lname data from the database and print certain fields. It seems as though the row[fname] and row[lname] doesn't work... is there another way to do this? I keeps saying fname is not defined.
import sqlite3
connection = sqlite3.connect('shop.db')
cursor = connection.cursor()
create_table = '''
CREATE TABLE IF NOT EXISTS employee (
staff_ID INTEGER PRIMARY KEY,
password CHAR(4),
fname VARCHAR(20),
lname VARCHAR(30));'''
cursor.execute(create_table)
staffid = input('staff id: ')
password = input('password: ')
cursor.execute('SELECT * FROM employee WHERE staff_ID=? AND password=?', [staffid, password])
row = cursor.fetchone()
if row != None:
print(row[fname]+' '+row[lname])
You may insert any values into this table, I just didn't want the code to look too bulky... Thanks!
How do i write a query if the multiple form field data are being searched in mysql database.
The form fields are as follow
FirstName:
LastName:
Age:
Gender:
Now we can enter data in any multiple field and make a search
the code i have tried works for single field. Unable to create for multiple conditions
sql = "select * from PERSON where F_Name = %s or L_Name = %s or Age = %s and Gender = %s"
self.cursor.execute(sql,(self.fname, self.lname, self.age, self.gender))
If field FirstName and Gender are filled
If field Lastname, Gender, age are filled
If field FirsName, Age are filled
If field Gender and lastname are filled
like all possible conditions
This is not python or any language specific. This is about query syntax.
Try this
sql = "select * from PERSON where (F_Name = '%s' or L_Name = '%s' or Age = '%s') and Gender = '%s';"
self.cursor.execute(sql % (self.fname, self.lname, self.age, self.gender))
Refer this http://www.tuxradar.com/practicalphp/9/3/13