Insert record into PostgreSQL table using default DB values
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.
Re: Insert record into PostgreSQL table using default DB values
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:
Code:
ALTER TABLE mytable
ALTER COLUMN myid
SET DEFAULT NEXTVAL('mytable_myid_seq');
Re: Insert record into PostgreSQL table using default DB values
Yes. I have already done it. But how should look C++ Qt code.
Re: Insert record into PostgreSQL table using default DB values
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.
Re: Insert record into PostgreSQL table using default DB values
Quote:
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:
Code:
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.