Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. PostgreSql and problem with lastInsertId()
Forum Update on Monday, May 27th 2025

PostgreSql and problem with lastInsertId()

Scheduled Pinned Locked Moved General and Desktop
3 Posts 2 Posters 3.8k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • H Offline
    H Offline
    Hostel
    wrote on 9 Sept 2011, 16:38 last edited by
    #1

    I have a problem with method lastInsertId. I'm using a PostgreSql 8.4 and Qt 4.6.3 under Linux. I have a code like this:
    @
    // _model is a QSqlTableModel
    QSqlRecord record = _model->record();
    _model->insertRecord( -1, record );

    SomeDialog* dialog = new SomeDialog( _model );
    dialog->exec();
    if( dialog->result() == QDialog::Accepted )
    {
        bool ok = _model->submitAll();
        if( ok )
        {
            // allways 0 but in db is a new record
            qDebug() << _model->query().lastInsertId().toInt();
        }
        else
        {
            qDebug() << _model->lastError().text();
        }
    }
    

    @

    My table looks like this:

    @
    CREATE TABLE mytable
    (
    id serial NOT NULL,
    field1 text,
    CONSTRAINT mytable_pkey PRIMARY KEY (id),
    )
    WITH (
    OIDS=TRUE
    );
    @

    How can I get a inserted ID? I need select new row in QTableView and I need this information.

    1 Reply Last reply
    0
    • L Offline
      L Offline
      lgeyer
      wrote on 9 Sept 2011, 18:21 last edited by
      #2

      As far as I know lastInsertId() for PostgreSQL is supported at least with Qt 4.7. If this is not an option for you you might try the "RETURNING":http://www.postgresql.org/docs/8.3/interactive/sql-insert.html clause in your queries.

      1 Reply Last reply
      0
      • H Offline
        H Offline
        Hostel
        wrote on 9 Sept 2011, 18:42 last edited by
        #3

        Thanks for reply. Tomorrow I will test Qt 4.7. lastInsertId() returns a OIDS number from Pg(I know from Qt doc), but only in QSqlQuery(I tested this a few minuts ago), but with QSqlTableModel return always 0. I known a RETURNING but I want to stay with QSqlTableModel. Maybe I will change a little driver to Pg to implement a insert with returning. I need think about it what would be better.

        1 Reply Last reply
        0

        1/3

        9 Sept 2011, 16:38

        • Login

        • Login or register to search.
        1 out of 3
        • First post
          1/3
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved