thank you...was not at a linux computer so no synaptic
Last edited by jimi_hendrix; October 9th, 2008 at 12:09 PM.
Anyone know of a good Python + Sqlite tutorial?
Blog | I'm available for programming contributions. C & Python.
Intel Core i7 920 | EVGA x58 SLI | NVidia GeForce 8600 GT | WD 500GB HDD | Corsair XMS3 3GB | Ubuntu 9.04
Here is the one I used:
http://www.devshed.com/c/a/Python/Using-SQLite-in-Python/
Also, here is my attempt at this challenge. I hope that I'll add the query support that LaRoza mentioned, but this is all I have time for now and I wanted to get the bulk of it up for feedback.
There must be a better way of handling the database connection than passing it all over the place the way I've been doing. Any ideas? I thought of creating a class with methods to insert and query from the database, but I'm not sure if that's the ideal way.
The program uses the database my.db, creating it if it doesn't exist.
As always, a big thank you to LaRoza and to anybody with feedback and advice.
Edit: Added a commit() to the insert_record() function, so that data persists from session to session. Also fixed the output formatting to make it look better. Still not as good as OutOfReach's, but not too bad.PHP Code:
#!/usr/bin/python
import pysqlite2.dbapi2 as sqlite
import os
def connect_to_db(filename):
if not os.path.exists(filename):
create_db(filename)
return sqlite.connect(filename)
def create_db(filename):
if os.path.exists(filename):
return False
db = sqlite.connect(filename)
db.execute("CREATE TABLE main ('name' NOT NULL, 'age' INTEGER NOT NULL)")
def insert_record(db, name, age):
db.execute('INSERT INTO main VALUES (?, ?)', (name, age))
db.commit()
def get_records(db):
cursor = db.execute('SELECT * FROM main')
return cursor.fetchall()
def iface_input(db):
os.system("clear")
people = []
name = raw_input("Enter the first name. Type 'exit' to quit. > ")
while name.lower().strip() != 'exit':
verified = False
while not verified:
age = raw_input("Enter " + name + "'s age. > ")
if age.strip().isdigit():
people.append((name, age))
verified = True
else:
print "Ages must be entered as positive integers. Please try again."
name = raw_input("Enter the next name. Type 'exit' to quit. > ")
for person in people:
insert_record(db, *person)
print "Names entered."
iface_main(db)
def iface_retrieve(db):
os.system("clear")
records = get_records(db)
nameLength = 0
for record in records:
if len(record[0]) > nameLength:
nameLength = len(record[0])
print "Name".ljust(nameLength), "Age".rjust(11)
for record in records:
print record[0].ljust(nameLength), '===>', str(record[1]).ljust(5)
print '\n\n'
raw_input("Press Enter to return to Main Menu.")
iface_main(db)
def iface_main(db):
os.system("clear")
print "What would you like to do?"
print " 1 Input data"
print " 2 Retrieve data"
print " 3 Quit\n\n"
verified = False
while not verified:
option = raw_input("Enter the number of your choice. > ")
option = option.strip().rstrip('.')
if option == '1':
verified = True
iface_input(db)
elif option == '2':
verified = True
iface_retrieve(db)
elif option == '3':
import sys
sys.exit()
else:
print "Please choose a number from 1 to 3."
if __name__ == "__main__":
db = connect_to_db("my.db")
iface_main(db)
Last edited by SteelDragon; October 10th, 2008 at 05:12 AM.
My wiki? http://laroza77.wikidot.com/sqlite
This may be an interesting job for the Query language described at http://mitpress.mit.edu/sicp/full-te...ml#%_sec_4.4.1
That looks cool. I may just have to do this challenge again .
On a related note, after the last programming challenge I started looking into Lisp and came across the book in your link, as well as How to Design Programs, which appeared pretty similar to my eyes. Since I know nothing about Scheme and little about programming at all, I couldn't make an educated as to which to read first. For some reason which I can't remember, I opted for HTDP and am working through it now. Any opinions on which is better or what significant differences there are between the two? That query language example looked really cool and handy, and if I don't come across something that impressive in my book, I'll regret my choice . I intend to stick it out and have bookmarked SICP for later, so I'd really like knowledgeable opinions on either of both sources.
Cheers.
Here's mine after some hours of reading and practice:
PHP Code:
import pysqlite2.dbapi2 as sqlite
import os
class Database(object):
def __init__(self):
self.setup()
self.user_input()
def setup(self):
exists = None
if not os.path.exists("Name_Age.db"): exists = False
self.connection = sqlite.connect("Name_Age.db")
self.cursor = self.connection.cursor()
if exists == False:
self.cursor.execute('CREATE TABLE information (id INTEGER PRIMARY KEY, name VARCHAR(50), age VARCHAR(50))')
del exists
def writeToDatabase(self):
try:
name = str(raw_input("What is your name?: "))
age = int(raw_input("Your age?: "))
except Exception, e:
print "Wrong Input"
self.cursor.execute('INSERT INTO information VALUES (null, ?, ?)', (name, age))
self.connection.commit()
def read_database(self):
self.cursor.execute("SELECT * FROM information")
for x in self.cursor:
print "-"*10
print "Name: %s" % x[1]
print "Age: %s" % int(x[2])
print "-"*10
def user_input(self):
choice = raw_input("Would you like to read your database or write to it? [r|w]: ")
if choice.lower() in ("r", "read", "1"):
self.read_database()
elif choice.lower() in ("w", "write", "2"):
self.writeToDatabase()
if __name__ == "__main__":
Database()
Learning SQLite was much easier than I thought it would've been. :S
Blog | I'm available for programming contributions. C & Python.
Intel Core i7 920 | EVGA x58 SLI | NVidia GeForce 8600 GT | WD 500GB HDD | Corsair XMS3 3GB | Ubuntu 9.04
why are you putting your database statements inside the class?
PHP alpha version
Code:<?php $db = "names.db"; $tablename="names"; if ( $dbh = sqlite_open($db,0666,$sqliteerror) ){ $result = sqlite_query($dbh,"SELECT name FROM sqlite_master WHERE type='table' AND name='$tablename'"); if ( sqlite_num_rows($result) <= 0){ $cmd = "create table names( name VARCHAR(30) NOT NULL, age INTEGER NOT NULL)"; $q = sqlite_query($dbh,$cmd); } } echo "Enter name: "; $name = trim(fgets(STDIN)); echo "Age: "; $age = trim(fgets(STDIN)); print "Your name is ".$name." and age is: ".$age."\n"; if ( (!is_numeric($age)) || $age>130 || strlen($name) > 64 ){ echo "Invalid input.\n"; exit(); } $q = "select * from '$tablename' where name = '$name'"; $result = sqlite_query($dbh,$q); if ( sqlite_num_rows($result) > 0){ while ( $row = sqlite_fetch_array($result,SQLITE_ASSOC) ) { echo 'Name: ' . $row['name'] . ' Age: ' . $row['age']."\n"; } }else{ $q = "insert into names values('$name',$age)"; $result = sqlite_query($dbh,$q); } sqlite_close($dbh); ?>
Last edited by ghostdog74; October 10th, 2008 at 11:23 AM.
Take also a look at the SICP videos 8a and 8b at http://groups.csail.mit.edu/mac/clas...sman-lectures/ (well, better take a look at all of them... they're great "programming in general" lectures and also great Scheme lectures).
Bookmarks