PDA

View Full Version : Insert record into PostgreSQL table using default DB values



m15ch4
9th May 2011, 10:21
Hello.

I am trying to insert new row into table using QSqlTableModel's insertRows() and setData() methods. In my table I have ID field which is filled using Posgresql sequence.

How can I insert new row and not to worry about ID value. When I insert row using sql INSERT statement I just ommit ID (database fills it for me).

Thanks.

ChrisW67
9th May 2011, 10:34
Generally, if you don't set a value for a column in a newly inserted model row, and that column has a default value in the underlying database, then that column will take on the default value when the changes are committed to the database. This should work fine with PostgreSQL if your "id" column is defined something like this:


ALTER TABLE mytable
ALTER COLUMN myid
SET DEFAULT NEXTVAL('mytable_myid_seq');

m15ch4
9th May 2011, 12:28
Yes. I have already done it. But how should look C++ Qt code.

ChrisW67
9th May 2011, 23:48
Call QSqlTableModel::insertRows(), call setData() a number of times to set what you want in the new row (don't set the id column), move to another row or submitAll() the row (depends on edit strategy). This is all straight out of the manual, nothing tricky.

If you are having problems, provide us with some idea of what you are actually doing, what you expect to see, and what you actually see.

m15ch4
10th May 2011, 13:19
Call QSqlTableModel::insertRows(), call setData() a number of times to set what you want in the new row (don't set the id column), move to another row or submitAll() the row (depends on edit strategy). This is all straight out of the manual, nothing tricky.
This method doesn't work.

For now I use:

void DBEngine::beforeInsertRec(QSqlRecord &record)
{
record.setGenerated(0, false);
}

slot connected to beforeInsert(QSqlRecord &record) signal to set ID field to not be generated in sql query.

I've found this solution in this forum.

Thanks.