Thread: INSERT results

INSERT results

From
Mark Thomas
Date:
Suppose I have a sequence/table:

CREATE SEQUENCE "id_seq" start 5000 increment 1;

CREATE TABLE "users"
(
     "id" integer primary key default nextval('id_seq') NOT NULL,
     "name" varchar(64)
);

I'm using libpq. If I do something like this:

PGconn *conn; // assume initialized
const char *q = "INSERT INTO users (name) VALUES ('J Doe')";
PGresult *res = PQexec(conn, q);

At this point is there any way for my app to determine the id value of the
newly inserted record?



Mark Thomas
---
thomas@pbegames.com ----> http://www.pbegames.com/~thomas
Play by Electron Games -> http://www.pbegames.com Free Trial Games


Re: INSERT results

From
"Joshua b. Jore"
Date:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

So I'm not a libpq programmer. I would guess that you might have access to
the OID of the row and you could SELECT the id using that. Here's another
thought, define a function something like this:

CREATE FUNCTION foo(VARCHAR) RETURNS INTEGER AS '
DECLARE
    N ALIAS FOR $1;
    I INTEGER;
BEGIN
    -- maybe you have to select the value into the int
    I := nextval(''''idseq'''');
    INSERT INTO ....
    RETURN I;
END;
' LANGUAGE 'plpgsql' WITH (isstrict);

Also, there is a datatype named 'name'. You'll be happier if you rename
your "name" column to something else like "username".

Joshua b. Jore
http://www.greentechnologist.org

On Tue, 23 Apr 2002, Mark Thomas wrote:

> Suppose I have a sequence/table:
>
> CREATE SEQUENCE "id_seq" start 5000 increment 1;
>
> CREATE TABLE "users"
> (
>      "id" integer primary key default nextval('id_seq') NOT NULL,
>      "name" varchar(64)
> );
>
> I'm using libpq. If I do something like this:
>
> PGconn *conn; // assume initialized
> const char *q = "INSERT INTO users (name) VALUES ('J Doe')";
> PGresult *res = PQexec(conn, q);
>
> At this point is there any way for my app to determine the id value of the
> newly inserted record?
>
>
>
> Mark Thomas
> ---
> thomas@pbegames.com ----> http://www.pbegames.com/~thomas
> Play by Electron Games -> http://www.pbegames.com Free Trial Games
>
>
> ---------------------------(end of broadcast)---------------------------
> TIP 3: if posting/reading through Usenet, please send an appropriate
> subscribe-nomail command to majordomo@postgresql.org so that your
> message can get through to the mailing list cleanly
>
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (OpenBSD)
Comment: For info see http://www.gnupg.org

iD8DBQE8xdo2fexLsowstzcRAoxsAJ0aLgju7HCd3AHwGx2BM32eu5Fa9wCg2con
7kknNzNKeaXYtL7sSLtjK3M=
=CWiK
-----END PGP SIGNATURE-----