Perl DBI and Inserting

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • savanm
    New Member
    • Oct 2006
    • 85

    Perl DBI and Inserting

    Hi all,

    Here I want to insert a row into a table.

    Am using Mysql.How to use insert query in PERLDBI

    Here is my sample Code

    Code:
    use strict;
    use DBI;
    
    my $dbh = DBI->connect("DBI:mysql:database=perldbi;host=localhost","root","");
    
    #$dbh->do("CREATE TABLE asdf (name VARCHAR(21),phone VARCHAR(21))");
    #$dbh->do("DROP TABLE asdf");
    
    my ($userid, $pass);
    my $sth = $dbh->prepare("SELECT * FROM foo1");
    $sth->execute();
    $sth->bind_columns(\$userid, \$pass);
    while ($sth->fetch) {
    	print "$userid		$pass\n";
    }
    $sth->finish();
    
    my $sthC = $dbh->prepare("insert TABLE (usrid,pass) values (navi,sava)");
    # or die "Couldn't prepare: $DBI::errstr";
    $sthC->execute('navi', 'sava');
    # or die "Couldn't execute: $DBI::errstr";
    $dbh->disconnect();
    Thanks
    Last edited by miller; Mar 30 '07, 05:02 PM. Reason: Code tag
  • KevinADC
    Recognized Expert Specialist
    • Jan 2007
    • 4092

    #2
    It should be covered in the Mysql driver documentation:

    cpan DBD::Mysql

    Comment

    • savanm
      New Member
      • Oct 2006
      • 85

      #3
      Hi Kevin,

      I got the solution,

      Code:
      print "Enter user id\n";
       my $usr = <STDIN>;	
       chomp($usr);
       print "Enter Password\n";
       my $pas = <STDIN>;
       chomp($pas);
       
      my $d=$dbh->do("INSERT INTO foo1 values('$usr','$pas')");
      print "Insert $d Rows\n";
      Thaks for ur help

      Comment

      • KevinADC
        Recognized Expert Specialist
        • Jan 2007
        • 4092

        #4
        Very good, you're welcome.

        Comment

        • miller
          Recognized Expert Top Contributor
          • Oct 2006
          • 1086

          #5
          Hi savanm,

          A better way to do that insert statement would be to use placeholders like this:

          Code:
          my $sthC = $dbh->prepare("INSERT INTO foo1 (usrid, pass) VALUES (?, ?)");
          my $count = $sthC->execute('navi', 'sava') or die $dbh->errstr;
          You were close to this method in your original solution. You simply hadn't put in the question marks.

          - Miller

          Comment

          Working...