本文整理汇总了C++中QSqlQuery::lastInsertId方法的典型用法代码示例。如果您正苦于以下问题:C++ QSqlQuery::lastInsertId方法的具体用法?C++ QSqlQuery::lastInsertId怎么用?C++ QSqlQuery::lastInsertId使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QSqlQuery
的用法示例。
在下文中一共展示了QSqlQuery::lastInsertId方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: save
void PlaceDialog::save()
{
QSqlQuery query;
if (m_placeID == -1) { // add place
query.prepare(QStringLiteral("INSERT INTO Places (name, lat, lon, comment) "
"VALUES (:name, :lat, :lon, :comment)"));
//qDebug() << "Adding place with query" << query.lastQuery();
} else { // update place
query.prepare(QStringLiteral("UPDATE Places SET name=:name, lat=:lat, lon=:lon, comment=:comment "
"WHERE id=:id"));
query.bindValue(":id", m_placeID);
}
query.bindValue(":name", ui->leName->text());
query.bindValue(":lat", ui->sbLat->value());
query.bindValue(":lon", ui->sbLon->value());
query.bindValue(":comment", ui->teComment->toPlainText());
if (!query.exec()) {
qWarning() << Q_FUNC_INFO << "Query failed with" << query.lastError().text();
return;
}
if (query.lastInsertId().isValid())
m_placeID = query.lastInsertId().toInt();
}
示例2: on_toolButton_add_maker_clicked
void DialogMySQLConfig::on_toolButton_add_maker_clicked()
{
QApplication::setOverrideCursor(Qt::WaitCursor);
QSqlQuery query;
query.prepare("INSERT INTO makers(maker,header) VALUES(?,?)");
query.addBindValue(m_ui->comboBox_makers->currentText());
query.addBindValue(m_ui->textEdit_doc_header->toHtml());
int l_maker=-1;
if(query.exec()) {
if(query.lastInsertId().isValid()) {
l_maker=query.lastInsertId().toInt();
}
}
m_ui->comboBox_makers->setMaxCount(0);
query.prepare("SELECT * FROM makers ORDER BY id");
if (query.exec()){
m_ui->comboBox_makers->setMaxCount(1000);
while (query.next()) {
m_ui->comboBox_makers->addItem(query.value(1).toString(),query.value(0).toString());
}
}
QApplication::restoreOverrideCursor();
if(l_maker >=0 ) {
m_ui->comboBox_makers->setCurrentIndex( m_ui->comboBox_makers->findData(l_maker));
QMessageBox::information(this, trUtf8("Добавлено"),trUtf8("Добавлен новый поставщик"));
}
}
示例3: VALUES
int sqlo::addgroup(project *p, QString nameproject, QString name, int groupparent, int type, QString description, int gquestion, int id)
{
QSqlQuery qry;
if (id != -1)
qry.prepare(("UPDATE project_" + p->name + "_groupe Set groupname=?, groupparent=?, type=?, description=?, gquestion=? WHERE id=?;"));
else
qry.prepare( "INSERT INTO project_" + nameproject + "_groupe (groupname ,groupparent ,type, description, gquestion) VALUES ( ?, ?, ?, ?, ? );" );
qry.addBindValue(name);
qry.addBindValue(QString::number(groupparent));
qry.addBindValue(QString::number(type));
qry.addBindValue(description);
qry.addBindValue(gquestion);
if (id != -1)
qry.addBindValue(id);
if( !qry.exec() )
qDebug() << qry.lastError();
else
qDebug() << "groupe insert success!";
if (id == -1)
p->addgroup(name, groupparent, qry.lastInsertId().toInt(), type, description, gquestion);
else
{
vector<group> *tmp = (type == 0) ? &p->listgroup : &p->listqgroup;
(*tmp)[id].parentid = groupparent;
(*tmp)[id].type = type;
(*tmp)[id].description = description;
(*tmp)[id].name = name;
(*tmp)[id].gquestion = gquestion;
}
return (qry.lastInsertId().toInt());
}
示例4: saveItems
void SampleModel::saveItems()
{
QSqlQuery *query = new QSqlQuery(DatabaseAccessor::getDb());
QSqlQuery *query_1 = new QSqlQuery(DatabaseAccessor::getDb());
QString sql = "";
QString sql_items = "";
int pos = -1;
sql = "INSERT INTO sample (sample_set_id, location_id, sample_date, water_type_id, comment) ";
sql += "VALUES (:sample_set_id,:location_id,:date,:water_id,:comment)";
query->prepare(sql);
sql_items = "INSERT INTO item_sample (sample_set_id, sample_id, item_id, value) VALUES (:set_id,:s_id, :i_id, :value)";
query_1->prepare(sql_items);
//Сохраняется информаци о пробе, без указания: какие параметры в ней содержатся.
//Параметры пробы могут быть сохранены только при обновлении пробы
while (!items_to_save.empty())
{
query->bindValue(":sample_set_id",Names::sample_set_id);
query->bindValue(":location_id",items_to_save.first()->getLocationId());
query->bindValue(":water_id", items_to_save.first()->getWaterId());
query->bindValue(":date", items_to_save.first()->getDate().toString("yyyy-MM-dd hh:mm"));
query->bindValue(":comment", items_to_save.first()->getComment());
query->exec();
pos = findItemInPosition(items_to_save.first()->getPosition());
items[pos]->setId(query->lastInsertId().toUInt());
QHash<unsigned int, ItemInSample>::iterator i;
unsigned int s_id = 0;
s_id = query->lastInsertId().toUInt();
for (i = items_to_save.first()->getComponents()->begin(); i != items_to_save.first()->getComponents()->end(); i ++)
{
query_1->bindValue(":set_id", Names::sample_set_id);
query_1->bindValue(":s_id", s_id);
query_1->bindValue(":i_id",i.value().getItemId());
query_1->bindValue(":value",i.value().getValue());
query_1->exec();
}
// iter->setChanged(0);
// }//for (i = items_to_update.first()->getComponents()->begin(); i != items_to_update.first()->getComponents()->end(); i ++)
items_to_save.removeFirst();
}
delete query;
}
示例5: getQuery
/*! Adds a test network to the database with known properties */
void TestDao::addTestNetwork1(){
//Initialize everything to do with the test network
resetTestNetwork1();
//Add network with known properties
QSqlQuery query = getQuery("INSERT INTO Networks (Name, Description) VALUES ('testNetwork1Name', 'testNetwork1Description')");
executeQuery(query);
testNetID = query.lastInsertId().toUInt();
//Add two neuron groups with neuron type 1
QString queryStr = "INSERT INTO NeuronGroups (NetworkID, Name, Description, Parameters, NeuronTypeID ) VALUES (";
queryStr += QString::number(testNetID) + ", " + "'name1', 'desc1', '" + getConnectionParameterXML() + "', 1)";
query = getQuery(queryStr);
executeQuery(query);
neurGrp1ID = query.lastInsertId().toUInt();
executeQuery("INSERT INTO IzhikevichExcitatoryNeuronParameters (NeuronGroupID) VALUES (" + QString::number(neurGrp1ID) + ")");
queryStr = "INSERT INTO NeuronGroups (NetworkID, Name, Description, Parameters, NeuronTypeID ) VALUES (";
queryStr += QString::number(testNetID) + ", " + "'name2', 'desc2', '" + getNeuronParameterXML() + "', 1)";
query = getQuery(queryStr);
executeQuery(query);
neurGrp2ID = query.lastInsertId().toUInt();
executeQuery("INSERT INTO IzhikevichExcitatoryNeuronParameters (NeuronGroupID) VALUES (" + QString::number(neurGrp2ID) + ")");
//Create connection group between the two neuron groups
queryStr = "INSERT INTO ConnectionGroups (NetworkID, Description, FromNeuronGroupID, ToNeuronGroupID, Parameters, SynapseTypeID ) VALUES (";
queryStr += QString::number(testNetID) + ", 'conngrpdesc1', " + QString::number(neurGrp1ID) + ", " + QString::number(neurGrp2ID) + ", '" + getConnectionParameterXML() + "', 1)";
query = getQuery(queryStr);
executeQuery(query);
connGrp1ID = query.lastInsertId().toUInt();
//Add neurons to the groups, storing database id in testNeurIDList
testNeurIDList.clear();
testNeurIDList.append(addTestNeuron(neurGrp1ID, -1, -5, -6));
testNeurIDList.append(addTestNeuron(neurGrp1ID, 0, -1, 0));
testNeurIDList.append(addTestNeuron(neurGrp1ID, 9, -4, 0));
testNeurIDList.append(addTestNeuron(neurGrp2ID, 0, -1, 10));
testNeurIDList.append(addTestNeuron(neurGrp2ID, -3, -7, 5));
//Add test connections
testConnIDList.append(addTestConnection(connGrp1ID, testNeurIDList[0], testNeurIDList[1], 0.1, 1.1));//0
testConnIDList.append(addTestConnection(connGrp1ID, testNeurIDList[0], testNeurIDList[2], 0.2, 1.2));//1
testConnIDList.append(addTestConnection(connGrp1ID, testNeurIDList[0], testNeurIDList[3], 0.3, 1.3));//2
testConnIDList.append(addTestConnection(connGrp1ID, testNeurIDList[4], testNeurIDList[3], 0.4, 1.4));//3
testConnIDList.append(addTestConnection(connGrp1ID, testNeurIDList[4], testNeurIDList[1], 0.5, 1.5));//4
testConnIDList.append(addTestConnection(connGrp1ID, testNeurIDList[3], testNeurIDList[2], 0.6, 1.6));//5
executeQuery("INSERT INTO IzhikevichSynapseParameters (ConnectionGroupID) VALUES (" + QString::number(connGrp1ID) + ")");
}
示例6: insertCliente
int DatabaseManager::insertCliente(QString nombre, QString apellido, QString empresa, QString email, QString telefonofijo, QString telefonocelular,QString direccion, int ciudades_cp)
{
if(!db.open()){ QMessageBox::critical(0,"Database Error",db.lastError().text()); return -2; }
QSqlQuery preQuery;
preQuery.exec(QString("SELECT idcliente FROM clientes WHERE nombre = '%1' AND apellido = '%2' AND empresa = '%3' AND email = '%4' AND telefonofijo = '%5' AND telefonocelular = '%6' AND direccion = '%7' AND ciudades_cp = '%8' LIMIT 1;"
).arg(nombre).arg(apellido).arg(empresa).arg(email).arg(telefonofijo).arg(telefonocelular).arg(direccion).arg(ciudades_cp));
if(preQuery.next())
{
//There is a record in the table with this same information
qDebug() << "Client already exist";
return preQuery.value(0).toInt();
}
QSqlQuery query;
bool ret = query.exec(QString("INSERT INTO clientes (nombre, apellido, empresa, email, telefonofijo, telefonocelular, direccion, ciudades_cp) VALUES('%1','%2','%3','%4','%5','%6','%7','%8');"
).arg(nombre).arg(apellido).arg(empresa).arg(email).arg(telefonofijo).arg(telefonocelular).arg(direccion).arg(ciudades_cp));
if(ret)
{
return query.lastInsertId().toInt();
}
else
{
qDebug() << query.lastError().text();
return -1;
}
}
示例7: insertTransaccion
int DatabaseManager::insertTransaccion(QString idserie,QString prioridad, QString accesorios, QString observaciones, int clientes_idcliente, int balanzas_idbalanza, QString prestables_idprestable, int ubicaciones_idubicacion, QString dateTime)
{
if(!db.open()){ QMessageBox::critical(0,"Database Error",db.lastError().text()); return -2; }
QSqlQuery preQuery;
preQuery.exec(QString("SELECT idtransaccion FROM transacciones WHERE idserie = '%1' AND clientes_idcliente = '%2' AND balanzas_idbalanza = '%3' AND fecha_retirada IS NULL LIMIT 1;"
).arg(idserie).arg(clientes_idcliente).arg(balanzas_idbalanza));
if(preQuery.next())
{
//There is a record in the table with this same information
qDebug() << "Transaction already exist";
return preQuery.value(0).toInt();
}
QSqlQuery query;
bool ret = query.exec(QString("INSERT INTO transacciones (idserie, prioridad, accesorios, observaciones, clientes_idcliente, balanzas_idbalanza, prestables_idprestable, ubicaciones_idubicacion, fecha_ingresada) VALUES('%1','%2','%3','%4','%5','%6',%7,'%8','%9');"
).arg(idserie).arg(prioridad).arg(accesorios).arg(observaciones).arg(clientes_idcliente).arg(balanzas_idbalanza).arg(prestables_idprestable).arg(ubicaciones_idubicacion).arg(dateTime));
if(ret)
{
return query.lastInsertId().toInt();
}
else
{
qDebug() << query.lastError().text();
qDebug() << query.lastQuery();
return -1;
}
}
示例8: addPerson
bool DbManager::addPerson(const Person *person) {
if(person && person->isSufficient()) {
QSqlQuery query;
QString query_string = "INSERT INTO people (first_name, last_name, personal_code, job, email, phone) "
"VALUES (:first_name, :last_name, :personal_code, :job, :email, :phone)";
query.prepare(query_string);
query.bindValue(":first_name", person->getFirst_name());
query.bindValue(":last_name", person->getLast_name());
query.bindValue(":personal_code", person->getPersonal_code());
query.bindValue(":job", person->getJob());
query.bindValue(":email", person->getEmail());
query.bindValue(":phone", person->getPhone());
if(query.exec()) {
int id_person = query.lastInsertId().toInt();
addAddress(id_person, person->getAddress());
int id_license = getIdLicense(person->getLicense());
if(id_license > 0) {
addLicenseToPerson(id_person, id_license, person->getDateOfIssue());
}
return true;
}
}
return false;
}
示例9: storeContactInfo
void ChannelWatcher::storeContactInfo()
{
QSqlQuery insertContactIdQuery;
insertContactIdQuery.prepare(QStringLiteral("INSERT INTO contactData VALUES (NULL, :contactId, :displayName);"));
insertContactIdQuery.bindValue(QStringLiteral(":contactId"), m_channel->targetContact()->id());
const KPeople::PersonData person(QStringLiteral("ktp://") + m_accountObjectPath.mid(35) + QStringLiteral("?") + m_channel->targetContact()->id());
insertContactIdQuery.bindValue(QStringLiteral(":displayName"), person.name());
if (!m_db.transaction()) {
qWarning() << "Cannot get a transaction lock for inserting contact data!";
}
if (insertContactIdQuery.exec()) {
m_db.commit();
m_contactDbId = insertContactIdQuery.lastInsertId().toUInt();
} else {
qWarning() << "Inserting contact data into database has failed:" << insertContactIdQuery.lastError().text();
m_db.rollback();
// Now we assume here that it failed because of the UNIQUE constraint
// so try to get the id from the database, assuming it already exists
QSqlQuery selectContactId;
selectContactId.prepare(QStringLiteral("SELECT id FROM contactData WHERE targetContact = :targetContact"));
selectContactId.bindValue(QStringLiteral(":targetContact"), m_channel->targetContact()->id());
selectContactId.exec();
if (!selectContactId.lastError().isValid() && selectContactId.first()) {
m_contactDbId = selectContactId.value(0).toUInt();
} else {
qWarning() << "Error while getting contact id from database:" << selectContactId.lastError().text();
}
}
}
示例10: maas
void smaas::maasKaydet2(QStringList &listSilinenMaas,QTableWidget* tblMaas)
{
QSqlQuery query;
//yeni eklenen kayıtlar
for(int i=0;i<tblMaas->rowCount();i++)
{
if(tblMaas->item(i,dgs.msSutunKayit)->text()=="0")
{
query.exec(QString("insert into maas(m_tarih, m_calisan, m_maas, m_ay, m_tur, m_hesap) values ('%1', '%2', '%3', '%4', '%5', '%6')").arg(tblMaas->item(i,dgs.msSutunTarih)->text()).arg(tblMaas->item(i,dgs.msSutunCalisan)->text()).arg(tblMaas->item(i,dgs.msSutunMaas)->text()).arg(tblMaas->item(i,dgs.msSutunAy)->text()).arg(tblMaas->item(i,dgs.msSutunTur)->text()).arg(tblMaas->item(i,dgs.msSutunHesap)->text()));
tblMaas->item(i,dgs.msSutunKayit)->setText(query.lastInsertId().toString());
}
}
////////////////////////
//silinen kayıtlar
for(int i=0;i<listSilinenMaas.count();i++)
{
query.exec(QString("delete from maas where m_id='%1'").arg(listSilinenMaas.at(i)));
}
//////////////////////
//değiştirilen kayıtlar
for(int i=0;i<tblMaas->rowCount();i++)
{
if(tblMaas->item(i,dgs.msSutunDegisim)->text()=="1")
{
query.exec(QString("update maas set m_tarih='%1', m_calisan='%2', m_maas='%3', m_ay='%4', m_tur='%5', m_hesap='%7' where m_id='%6'").arg(tblMaas->item(i,dgs.msSutunTarih)->text()).arg(tblMaas->item(i,dgs.msSutunCalisan)->text()).arg(tblMaas->item(i,dgs.msSutunMaas)->text()).arg(tblMaas->item(i,dgs.msSutunAy)->text()).arg(tblMaas->item(i,dgs.msSutunTur)->text()).arg(tblMaas->item(i,dgs.msSutunKayit)->text()).arg(tblMaas->item(i,dgs.msSutunHesap)->text()));
tblMaas->item(i,dgs.msSutunDegisim)->setText("0");
}
}
/////////////////////
}
示例11: on_buttonBox_accepted
void CSinglePrealertEdit::on_buttonBox_accepted()
{
if(m_newAlert)
{
for(int j = 0; j < m_Prealerts->count(); j++)
{
QSqlQuery lqry;
lqry.prepare("INSERT INTO tblPrealert (DDate, PersID) VALUES (:Date, :PID);");
lqry.bindValue(":Date", m_Prealerts->at(j).Date().toString("yyyy-MM-dd"));
lqry.bindValue(":PID", m_actPers->id());
lqry.exec();
int ppid = lqry.lastInsertId().toInt();
for(int i = 0; i < m_paTypes->count(); i++)
{
QSqlQuery ltqry;
ltqry.prepare("INSERT INTO tblPATypes (PAID, TypeID) VALUES (:PAID, :TID);");
ltqry.bindValue(":PAID", ppid);
ltqry.bindValue(":TID", m_paTypes->at(i).type()->id());
ltqry.exec();
}
}
}
else
{
}
close();
}
示例12: insert
/*!
* \brief insert a new obj into the table behaviortask
* \param obj a pointer to the object with of the new obj
* \return an integer id of new row
* \retval -1 if fail.
*/
int BehaviorTaskDAO::insert(BehaviorTaskObject * obj) {
if(!db->isOpen())
db->open();
QSqlQuery query;
bool ret = query.exec(QString("insert into behaviortask values ( NULL, %1, %2, %3, %4, %5, '%6')")
.arg(obj->getIDConn())
.arg(obj->getIDSubject())
.arg(obj->getIDTask())
.arg(obj->getTimeStart())
.arg(obj->getTimeEnd())
.arg(obj->getLabel()));
int newId = -1;
// Get database given autoincrement value
if (ret)
{
newId = query.lastInsertId().toInt();
}else{
qCritical() << query.lastQuery();
qCritical() << query.lastError();
qCritical() << db->lastError();
}
db->close();
return newId;
}
示例13: addToDb
void Message::addToDb()
{
QSqlQuery query;
query.prepare("INSERT INTO message ("
"direction, state, conversation_id, conversation, message_id, composed_time, received_time, content, signature, sender, encoding"
") VALUES ("
":direction, :state, :conversation_id, :conversation, :message_id, :composed_time, :received_time, :content, :signature, :sender, :encoding"
")");
assert(data_);
assert(data_->composedTime.isValid());
query.bindValue(":direction", static_cast<int>(direction_));
query.bindValue(":state", static_cast<int>(state_));
query.bindValue(":conversation_id", conversationId_);
query.bindValue(":conversation", data_->conversation);
query.bindValue(":message_id", data_->messageId);
query.bindValue(":composed_time", data_->composedTime);
query.bindValue(":received_time", sentReceivedTime_);
query.bindValue(":content", data_->content);
query.bindValue(":signature", data_->signature);
query.bindValue(":sender", data_->sender);
query.bindValue(":encoding", data_->encoding);
if(!query.exec()) {
throw Error(QStringLiteral("Failed to add Message: %1").arg(
query.lastError().text()));
}
id_ = query.lastInsertId().toInt();
LFLOG_INFO << "Added message " << data_->messageId.toHex()
<< " to the database with id " << id_;
}
示例14: addNote
QVariant Database::addNote(QSqlQuery &q, const QString &rawText, const QString &richText)
{
q.addBindValue(rawText);
q.addBindValue(richText);
q.exec();
return q.lastInsertId();
}
示例15: _addDataType
QVariant Database::_addDataType(QSqlQuery &q, int id, const QString &name)
{
q.addBindValue(id);
q.addBindValue(name);
q.exec();
return q.lastInsertId();
}