Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <QCoreApplication>
- #include <QSqlDatabase>
- #include <QSqlTableModel>
- #include <QSqlQuery>
- #include <QSqlError>
- #include <QSqlTableModel>
- #include <QSqlRecord>
- #include <QModelIndexList>
- #include <iostream>
- using namespace std;
- int main(int argc, char *argv[])
- {
- // DB Connection
- QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
- db.setHostName("127.0.0.1");
- db.setDatabaseName("your_database");
- db.setUserName("your_user_name");
- db.setPassword("your_password");
- if ( ! db.open())
- {
- cout << "Cannot open database" << endl;
- }
- // drop table
- cout << "drop table datatest..." << endl;
- QSqlQuery q = QSqlQuery(db);
- QString sql;
- sql = "drop table datatest;";
- q.exec(sql);
- // Create table
- cout << "create table datatest..." << endl;
- sql=
- "CREATE TABLE datatest"
- "("
- " id serial"
- " ,kode character(1)"
- " ,nama character(10)"
- " ,CONSTRAINT datatest_pkey PRIMARY KEY (id)"
- ")"
- " WITH ( OIDS = TRUE);";
- if ( ! q.exec( sql ))
- {
- cout << "error create table" << endl;
- cout << q.lastError().databaseText().toStdString() << endl;
- return 0;
- };
- // Populate 2 records
- cout << "Populate table..." << endl;
- sql = "insert into datatest (kode,nama) values (:kode,:nama)";
- q.prepare(sql);
- q.bindValue(":kode","A");q.bindValue(":nama","ALBERT"); q.exec();
- q.bindValue(":kode","Z");q.bindValue(":nama","ZORRO"); q.exec();
- // Create model
- cout << "Create QSqlTableModel..." << endl;
- QSqlTableModel model;
- model.setTable("datatest");
- model.select();
- // insert record
- cout << "Inserting a record to the model...";
- QSqlRecord record = model.record();
- record.setGenerated("id",false);
- record.setValue("kode","P");
- record.setValue("nama","PATRICK");
- if ( ! model.insertRecord(-1,record))
- {
- cout << "Error inserting record to the model" << endl;
- cout << model.lastError().databaseText().toStdString() <<endl;
- return 0;
- };
- // get the new record id
- int newRecId = model.query().lastInsertId().toInt();
- cout << ", field ID of the new record is " << newRecId << endl;
- // find the new inserted record
- QModelIndexList listNewRec = model.match(model.index(0,0),Qt::DisplayRole,newRecId);
- if ( listNewRec.size() == 1 )
- {
- cout << "Found the new record..." << endl;
- }
- else
- {
- cout << "Can not locate the new inserted record" << endl;
- }
- // reselect the model
- cout << "doing model.select()" << endl;
- model.select();
- // find the new inserted record
- listNewRec = model.match(model.index(0,0),Qt::DisplayRole,newRecId);
- if ( listNewRec.size() == 1 )
- {
- cout << "Found the new record only after reselect the model..." << endl;
- }
- else
- {
- cout << "Can not locate the new inserted record" << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement