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? -
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.
-
@M4RZB4Ni Use SQL count() function: http://www.w3schools.com/sql/sql_func_count.asp
-
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) orreplace 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 }