Page 2 of 4 FirstFirst 1234 LastLast
Results 11 to 20 of 32

Thread: [Beginner] Programming Challenge: 7

  1. #11
    Join Date
    Apr 2007
    Beans
    14,781

    Re: [Beginner] Programming Challenge: 7

    Quote Originally Posted by jimi_hendrix View Post
    odd...i cant figure out how to install sqlite...none of the files i try will install it
    Search in synaptic?

    Also, Python comes with it.

  2. #12
    Join Date
    Jul 2008
    Beans
    1,706

    Re: [Beginner] Programming Challenge: 7

    thank you...was not at a linux computer so no synaptic
    Last edited by jimi_hendrix; October 9th, 2008 at 12:09 PM.

  3. #13
    Join Date
    Jun 2008
    Location
    California, USA
    Beans
    1,030
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: [Beginner] Programming Challenge: 7

    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

  4. #14
    Join Date
    Mar 2007
    Beans
    Hidden!
    Distro
    Kubuntu 7.04 Feisty Fawn

    Re: [Beginner] Programming Challenge: 7

    Quote Originally Posted by OutOfReach View Post
    Anyone know of a good Python + Sqlite tutorial?
    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.

    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(dbnameage):
        
    db.execute('INSERT INTO main VALUES (?, ?)', (nameage))
        
    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((nameage))
                    
    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
    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.
    Last edited by SteelDragon; October 10th, 2008 at 05:12 AM.

  5. #15
    Join Date
    Apr 2007
    Beans
    14,781

    Re: [Beginner] Programming Challenge: 7

    Quote Originally Posted by OutOfReach View Post
    Anyone know of a good Python + Sqlite tutorial?
    My wiki? http://laroza77.wikidot.com/sqlite

  6. #16
    Join Date
    Apr 2007
    Location
    (X,Y,Z) = (0,0,0)
    Beans
    3,715

    Re: [Beginner] Programming Challenge: 7

    This may be an interesting job for the Query language described at http://mitpress.mit.edu/sicp/full-te...ml#%_sec_4.4.1

  7. #17
    Join Date
    Mar 2007
    Beans
    Hidden!
    Distro
    Kubuntu 7.04 Feisty Fawn

    Re: [Beginner] Programming Challenge: 7

    Quote Originally Posted by nvteighen View Post
    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.

  8. #18
    Join Date
    Jun 2008
    Location
    California, USA
    Beans
    1,030
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: [Beginner] Programming Challenge: 7

    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 Exceptione:
                    print 
    "Wrong Input"
                
    self.cursor.execute('INSERT INTO information VALUES (null, ?, ?)', (nameage))
                
    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

  9. #19
    Join Date
    Sep 2006
    Beans
    2,914

    Re: [Beginner] Programming Challenge: 7

    Quote Originally Posted by OutOfReach View Post
    Here's mine after some hours of reading and practice:
    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.

  10. #20
    Join Date
    Apr 2007
    Location
    (X,Y,Z) = (0,0,0)
    Beans
    3,715

    Re: [Beginner] Programming Challenge: 7

    Quote Originally Posted by SteelDragon View Post
    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.
    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).

Page 2 of 4 FirstFirst 1234 LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •