简体   繁体   中英

Inserting into a PostgreSQL table using Perl

I am trying to auto-populate a table in a PostgreSQL database. Unfortunately I am not getting the insert statement to work.

The first row is an ID which is an integer, and the second column is of numeric data type. I am using a Perl script to achieve this.

I am using the rand function which creates random numbers between 0 and 1. The first argument is the variable $id ; the second argument is the variable $count .

Based on the count, the table will populate the ID followed by a random number.

I am using PostgreSQL 9.2.4.

-ID | Random_Number
-1 |  0.01
-1 |  0.03
-2 |  0.0566

#!/usr/bin/perl

use DBI;

my $id = <>;
my $count = <>;

my $db_host = 'localhost';
my $db_user = 'postgres';
my $db_pass = '12345';
my $db_name = 'postgres';

my $db = "dbi:Pg:dbname=${db_name};host=${db_host}";

$dbh = DBI->connect($db, $db_user, $db_pass, { RaiseError => 1, AutoCommit => 0 })
        || die "Error connecting to the database: $DBI::errstr\n";

for (my $loop = 0; $loop < $count; $loop++) {
    my $random_number = rand();
    my $loop++;
    my $query = "insert into random_table values($loop,$random_number)";
}

This is unnecessarily complex. Just:

CREATE TABLE random_table(id integer, random_value float);

then:

my $dbh = DBI->connect($db, $db_user, $db_pass,{ RaiseError => 1, AutoCommit => 0 })
my $sth $dbh->prepare("INSERT INTO random_table(id,random_value) SELECT x, random() FROM generate_series(?,?);")
my $result = $sth->execute(0, $count);

(Untested but I'm pretty sure that's right).

BTW, you really need to:

use strict;
use warnings;
use 5.10.1; // or whatever the oldest Perl you support is

in your scripts.

First, you are redeclaring the $loop variable, which will mask its previous declaration. Since ++ on an undefined value = 1, $loop in $query is 1 each time.

for(my $loop=0; $loop < $count;$loop++)
{
  my $random_number = rand();
  my $loop++; # Shouldn't be here
  my $query = "insert into random_table values($loop,$random_number)";
}

If you had turned warnings on perl would have warned you about this.

Second, you are doing nothing with $query. It's just a string. You have to execute it, eg $dbh->do($query).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM