[racket] How to insert array into Postgresql using DB module

From: Ryan Culpepper (ryanc at ccs.neu.edu)
Date: Fri Jan 4 12:47:38 EST 2013

On 01/04/2013 12:08 PM, J G Cho wrote:
> Thank you.
>
> If I may ask another question, what is the best way to handle
> inserting a new record and fetching that ID?
>
> Is there a better way than what I am about to do below?
>
> ;; [String] -> ID
> (define (create! ... )
>
>    (define batch!
>      (lambda ()
>        (define prev-id
>          (query-value conn
>                       "SELECT id FROM tableORDER BY id DESC LIMIT 1"))
>        (query (my-conn)
>               "INSERT INTO table (cols ...) VALUES ($1, $2, $3, $4, $5)"
>               ...)
>        ;; return assuming the ID is one greater that prev-id
>        (+ 1 prev-id)))
>
>    (call-with-transaction conn
>                           batch!))

If you're using PostgreSQL, use an INSERT statement with a RETURNING 
clause (see http://www.postgresql.org/docs/9.0/static/sql-insert.html).

Ryan


Posted on the users mailing list.