vendion has asked for the wisdom of the Perl Monks concerning the following question:

I'm using the DBD::pg to work with my PostgreSQL server from my perl script. One of the columns in my database is using the Serial datatype to have the value auto incremented by Postgre. The way that I am currently working with it is by sending it a blank value

$compid = q[]

but that produces this error from Postgre

DBD::Pg::db do failed: ERROR: invalid input syntax for integer: "" at repairs.pl line 352, <> line 20. Error: could not insert data into database: ERROR: invalid input syntax for integer: "" at repairs.pl line 366 main::db_add_computer('probdesc', 'n/a', 'compid', '', 'custid', '000-000000', 'service', 'n/a', 'compsn', ...) called at repairs.pl line 280 main::print_form() called at repairs.pl line 106

Anyone know what I am doing wrong here? If not then I can try asking in the IRC channel for PostgreSQL

Replies are listed 'Best First'.
Re: Working with Postgresql serial data type in Perl
by Corion (Patriarch) on Dec 18, 2010 at 15:38 UTC

    Most likely, you want to send it a NULL value. You should be using DBI placeholders instead of interpolating data into a string, just to avoid SQL interpolation problems. See DBI for placeholders and http://bobby-tables.com/ for why.

    my $sth_insert = $dbh->prepare(<<'SQL'); insert into mytable (desc,compid) values (?, ?) SQL my ($description, $compid) = ("Some description", undef); $sth_insert->execute( $description, $compid );

    Update: Actually set the values to insert

      I am already using placeholders in my code, so I know that is not the issue.

Re: Working with Postgresql serial data type in Perl
by moritz (Cardinal) on Dec 18, 2010 at 15:40 UTC

    If you want to enter a specific integer, just pass it on to the database.

    If not, construct your query in a way that simply doesn't enter any value for the serial column. For example if the table has columns id and name, and id is serial, simply write something like

    my $sth = $dbh->prepare('INSERT INTO your_table(name) VALUES (?)'); $sth->execute($your_name);

      the integer that gets used doesn't matter to me it just has to be unique for each entry. I have not thought about not passing anything to anything to that column in the database.

        It's all in the excellent manual: datatype serial (also available in PDF )

        Note that:

        Prior to PostgreSQL 7.3, serial implied UNIQUE. This is no longer automatic. If you wish a serial column to have a unique constraint or be a primary key, it must now be specified, just like any other data type.

        (Btw: a hint regarding the database name: call it postgresql, postgres, or even Pg, but calling it 'Postgre' makes the same impression as writing PERL instead of Perl).