CS50 pset7 Houses import.py prolem - python

My script runs & I don't receive any errors but my students.db is always empty.
My print commands for debugging all seem to print the contents of the csv.
I guess it could the be insert but I can't find an issue with it.
My code is below, along with what I see when I try to view the DB through the CS50IDE.
Thanks in advance for any help.
import cs50
import csv
from sys import argv, exit
#if len(argv) != 2:
# print("Usage: python import.py characters.csv")
# exit(1)
# connect to db
db = cs50.SQL("sqlite:///students.db")
# iterate through the csv file
with open("characters.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
middle = ""
names = row["name"].split()
firstname = names[0]
if len(names) == 2:
middle = ""
lastname = names[1]
else:
middle = names[1]
lastname = names[2]
house = row["house"]
birth = row["birth"]
print(firstname)
print(middle)
print(lastname)
print(row["house"])
print(row["birth"])
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)", firstname, middle, lastname, house, birth)
Attempting to view DB in the IDE
~/pset7/houses/ $ sqlite3 students.db
SQLite version 3.22.0 2018-01-22 18:45:57
Enter ".help" for usage hints.
sqlite> .schema
CREATE TABLE students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
first VARCHAR(255),
middle VARCHAR(255),
last VARCHAR(255),
house VARCHAR(10),
birth INTEGER
);
CREATE TABLE sqlite_sequence(name,seq);
sqlite> select * from students
...>

It's probably because you forgot to put a semi-colon(;) at the end of your SELECT statement.
Try this instead:
SELECT * FROM students;

Related

Inserting data via Python into an SQLite table

I'm trying to solve this exercise, and I have no clue why my SQLite DB won't update. Here is what I tried. Any ideas would be much appreciated:
Also, I forgot how to keep the program running, I mean to keep showing the user the options he has :(
import sqlite3
conn = sqlite3.connect("Books")
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS Books(
id INT PRIMARY KEY,
title TEXT,
year INT);
""")
user_input = input ("Dear User, you have the following two options, two and only two (case sensitive): \n\t 1. INSERT \n\t 2. SHOW BOOKS \nPlease insert your comamnd here: <<< ")
if user_input == "1. INSERT":
book_id = input("Book id: ")
book_title = input("Book title: ")
book_year = input ("Book year of publication: ")
cursor.execute
(""" INSERT INTO Books (id, title, year) VALUES (?,?,?)
""", (book_id, book_title, book_year))
conn.commit()
print("Book inserted succesfully!")
elif user_input == "2. SHOW BOOKS":
cursor.execute("SELECT * FROM Books;")
all_results = cursor.fetchall()
print(all_results)
else:
print("Not a valid command. Try again! It's all case sensitive in Python, u know...")
if (conn):
conn.close()

Taking value from column in one sqlite3 table and inserting into another

I am trying to add a feature to my program where a teacher sets homework to users from a class they've made. There is a table for users where each user has a unique UserID, classname, firstname and surname. I am trying to take the userIDs of students who are in a certain class, and insert them into a HomeworkSet table. I am able to retrieve the userIDs successfully, but when I insert them into the HomeworkSet table, the values appear as (for example) ('2a1910e919a84230bfc2a7111160cade',), and I am not sure how I am meant to remove the brackets and apostraphes.
def Class_sethw():
homeworktoset = Homework_To_Set.get()
#print (homeworktoset)
conn = sqlite3.connect('MyComputerScience.db')
c = conn.cursor()
homeworkID = c.execute("SELECT HWID FROM HomeworkInfo WHERE HomeworkName = ?", (homeworktoset, )).fetchone()
print (homeworkID)
c.execute("SELECT UserID FROM users WHERE ClassName = ?", (ClassName_SetHWR, ))
homeworksetlist = c.fetchall()
print (homeworksetlist)
for i in (homeworksetlist):
#x = i
#firstname, lastname = x.split(" ")
c.execute('insert INTO HomeworkSet (HWID, StudentID)VALUES(?,?);', ((homeworkID[0]), str(i)))
conn.commit()
Label(sethw, text = "Homework Set!", fg = "GREEN").place(relx=0.205, rely=0.445, height=34, width=97)
This is the code I have used.
You should change this line:
for i in (homeworksetlist):
to:
for i in homeworksetlist:

Function runs in Iron Python (Python(x,y) Spyder2 IDE) but not in Python 2.7 Console

I am using the Spyder2 IDE in the python(x,y) package. The below function runs fine in Iron Python, but has errors when I run in the console. I need it to run in the console so that I can use Pyinstaller. The error I get is: "Error binding parameter 0. Probably unsupported type." The line showing the error is the "cur.execute" line. I'm also using Sqlite3 and getting text data from PYQT4 lineEdit fields.
Here is the code:
def update_clients(self):
#Get client id from list
cid = None
try:
cid = self.client_list_id()
except:
QtGui.QMessageBox.warning(self, 'Warning', 'You must first select a client before you update')
if cid:
#Get update items
first = self.lineEdit_c_first.text()
last = self.lineEdit_c_last.text()
add1 = self.lineEdit_c_address1.text()
add2 = self.lineEdit_c_address2.text()
city = self.lineEdit_c_city.text()
state = self.lineEdit_c_state.text()
zipp = self.lineEdit_c_zip.text()
phone = self.lineEdit_c_phone.text()
cell = self.lineEdit_c_phone_cell.text()
off = self.lineEdit_c_phone_office.text()
email = self.lineEdit_c_email.text()
notes = self.textEdit_c_notes.toPlainText()
#Update database
conn = sqlite3.connect('gibbs.db')
cur = conn.cursor()
sql = ("""
UPDATE clients
SET
firstname = ?,
lastname = ?,
address1 = ?,
address2 = ?,
city = ?,
state = ?,
zip = ?,
phone = ?,
officephone = ?,
cell = ?,
email = ?,
notes = ?
WHERE rowid = ?
""")
cur.execute(sql, (first, last, add1, add2, city, state, zipp, phone, off, cell, email, notes, cid,))
conn.commit()
conn.close()
QtGui.QMessageBox.information(self, 'Success', 'Database successfully updated')
Additionally, since the issue is somehow related to data types, here is the code that I used to create the database tables:
import sqlite3
def create_connection():
try:
conn = sqlite3.connect('gibbs.db')
return conn
except:
pass
return None
def create_clients():
try:
conn = create_connection()
print conn
c = conn.cursor()
c.execute("""
CREATE TABLE clients (
id INTEGER PRIMARY KEY,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
firstname TEXT,
lastname TEXT,
address1 TEXT,
address2 TEXT,
city TEXT,
state TEXT,
zip TEXT,
phone TEXT,
officephone TEXT,
cell TEXT,
email TEXT,
notes TEXT
)
""")
conn.close()
except:
print "table already exists"
I added the line print type(first), as suggested by #roganjosh, just before the query. When running the program, the result was different in the two consoles. The Iron Python console outputs: <type 'unicode'> and in Python 2.7 console it is: <class 'PyQt4.QtCore.QString'>.
I solved by adding the str() function when getting my text from the PYQT4 lineEdits. For example:
first = str(self.lineEdit_c_first.text())

python sqlite3 query with AND

I am trying to build a simple Address book GUI that has a wx.listbox, that holds all the names in the book, first and last. Once clicked, it will return the information attached to the name from a database file. Right now I have it working by just the last name, I am trying to match first and last names. I am not, really, familiar with the SQLite 3 commands and syntax.
The function is below, this works fine now, but I want to change the query to something like:
select * from AddressBook where Last like names[0] and First like names[1]
Any help would be great!
def onListBox(self, event):
name = event.GetEventObject().GetStringSelection()
names = name.split(',')###names[0]=Last name, names[1] = first name
cursor = db.cursor()
cursor.execute("select * from AddressBook where Last like ?",('%'+names[0]+'%',) )
result = cursor.fetchall()
return result
The query from your comment should work.
Here is a small working example:
import sqlite3
conn = sqlite3.connect("test.sql")
cursor = conn.cursor()
cursor.execute("create table address_book (first_name text, last_name text)")
names = [["John", "Smith"], ["Jane", "Smith"]]
for first_name, last_name in names:
cursor.execute("insert into address_book (first_name, last_name) values (?, ?)", (first_name, last_name))
cursor.execute("select * from address_book where first_name like ? and last_name like ?", ("%" + names[0][0] + "%", "%" + names[0][1] + "%"))
print(cursor.fetchall())
It prints:
[('John', 'Smith')]

insert or replace statement not working with sqlite3 and python

Everytime I run this through the python interpreter it writes new values. for example:
name = ben
age = 10
phone = 42045042
If I run it 10 times. I get 10 duplicates in my database. I know it has to be an easy fix, but I've been working on this for hours and can't figure it out.
conn = sqlite3.connect('addressbook.db')
cur=conn.cursor()
conn.execute('''
CREATE TABLE IF NOT EXISTS people(name TEXT,
age TEXT, phone TEXT, fblink TEXT)''')
conn.execute("INSERT OR REPLACE INTO people values (?, ?, ?, ?)", ben.displayPerson())
cursor = conn.execute("SELECT name, age, phone, fblink from people")
for row in cursor:
print "NAME = ", row[0]
print "AGE = ", row[1]
print "PHONE = ", row[2]
print "FACEBOOK LINK = ", row[3], "\n"
cur.close()
conn.commit()
conn.close()
There's no primary key field.
Make a primary key field.
For example:
conn.execute('''
CREATE TABLE IF NOT EXISTS people(name TEXT primary key,
age TEXT, phone TEXT, fblink TEXT)''')
REPLACE is executed when UNIQUE constraint violation occurs. Without primary key (or unique ..), it does not happen.
Your table has no primary key, and hence SQLite doesn't know what it should "OR REPLACE" since it has nothing to base replacing on. Add a primary key.

Categories

Resources