Search code examples
c++sql-serverqtqsqlquery

QSqlQuery row affected result


SHA256 sha256;
std::string s = sha256(pass.toStdString());

QString myquery = "declare @identifier nvarchar(100) = NEWID()\
        declare @user_name nvarchar(50) = '"+user+"'\
        declare @pass_word nvarchar(100) = '"+QString::fromStdString(s)+"'\
        declare @hint nvarchar(50) = '"+hint+"'\
        if NOT exists(select * from user_table where (userid=@identifier or username = @user_name))\
        insert into user_table (username,password,password_salt,userid) values(@user_name,@pass_word,@hint,@identifier)";
qDebug()<<myquery;
openSqlConnection();
QSqlQuery q3;
q3.exec(myquery);

After executing this query, I should see result which will be (1 row(s) affected) if executed successfully.

If username already exists in the database, the result will be

Command(s) completed successfully.

To see the result from the select I use q3.next().

How do I know that my query has been executed successfully?


Solution

  • How do I know that my query has been executed successfully?

    You have a number of options here. You could check either:

    Returns true and sets the query state to active if the query was successful; otherwise returns false.

    for example:

    if (!q3.exec(myquery))
        \\ show error
    

    An active QSqlQuery is one that has been exec()'d successfully but not yet finished with.

    for example:

    q3.exec(myquery);
    
    if (!q3.isActive())
        \\ show error
    

    QSqlError::NoError 0 No error occurred.

    for example:

    q3.exec(myquery);
    
    if (q3.lastError().type() != QSqlError::NoError)
        \\ show error
    

    If you pass the check (the one you have selected), you could process your query further, e.g. to see if the username already exists and how many rows have been affected.