SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot Da Mouse's Avatar
    Join Date
    Aug 2002
    Posts
    111
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Perl and databases

    can anyone give me an example script of connecting to a mySQL database then: SELECT * FROM users :with a for() loop to output it, the reason I'm asking for a premade script is so I can get the general feel of connecting to mySQL
    I am DaMouse
    Nobody can beat me so long as I'm stubborn -DaMouse
    Squeak

  2. #2
    SitePoint Enthusiast eych's Avatar
    Join Date
    Nov 2002
    Location
    Moscow, Russia
    Posts
    90
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Greetings.

    Here it is.

    Code:
    #!/usr/bin/perl
    
    use strict;
    use DBI;
    
    # connecting to mysql database (see sub below)
    my $dbh = mysql_connect();
    
    # preparing sql statement
    my $sth = $dbh->prepare('SELECT * FROM users');
    
    # executing sql statement
    $sth->execute || die $DBI::errstr;
    
    # going through the returned results, printing 'username'
    # and 'password' fields (we suppose they exist in users
    # table)
    while (my $row = $sth->fetchrow_hashref) {
      print $row->{username} . ' => ' . $row->{password}, "\n";
    }
    
    $sth->finish;
    
    # simple sub to connect to mysql database
    # db-name, db-host, db-port, db-username, db-password 
    # should be replaced with actual values before this sub can
    # be used
    sub mysql_connect {
      my $dsn = "DBI:mysql:db-name:db-host:dp-port";
      my $dbh = DBI->connect($dsn, db-username, db-password) || die $DBI::errstr;
      return $dbh;
    }
    
    END { $dbh->disconnect if $dbh; }
    Sergey Smirnov
    One of the Stuffed Guys
    http://www.stuffedguys.com


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
  •