Check if a row exists Update Record, otherwise insert In Database



  • Hello
    i want to add some records to a database But i want to when User
    Clicked on the Button Program in the Begning Check if a row exists Update The Record, otherwise insert in Table
    I searched in Google For This,But Only Found SQL STATMENTS FOR STORED PROCEDURES Not C++ Codes Or Notes
    Anybody can Help me Please?


  • Lifetime Qt Champion

    Hi,

    Which type of SQL database are you targeting ? If SQLite, then you can do it in one query directly.

    Otherwise (and since you don't want to use only SQL), you'll have to run a select query to check if what you search already exist and based on that, call either an insert or update query. All this using QSqlQuery.

    Hope it helps.



  • @SGaist
    Thanks
    I use SqlServer 2014
    i know this method
    but i dont know how we Understand that Record exists ?
    Can you Write a sample Example?
    Thanks again


  • Moderators



  • @M4RZB4Ni

    I have never used MSSQL Server but a quick search on <whatever> tells me that a simple insert into on duplicate key update (as in mysql) or replace into (sqlite) is not supported. (both needs unique constraints for several keys in the table)

    Examples how to solve this with SQL statements directly can be found here:

    http://stackoverflow.com/a/12202
    http://stackoverflow.com/a/108420



  • If you have SQL server why not just create a stored procedure in the server and call it in C++?! It's the best option under all circumstances.

    If you can't use that then use a select then use something like:

    bool alreadyExist = false;
    {
    QSqlQuery query;
    query.prepare("select * from MyTable where rowID=:rowID");
    query.bindValue(":rowID",rowID);
    if(!query.exec()){
    // select failed
    }
    alreadyExist = query.next();
    }
    if(alreadyExist){
    // update
    }
    else{
    //insert
    }
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.