Skip to content
This repository has been archived by the owner on Dec 18, 2021. It is now read-only.

How to return mysql auto incorrect when inserting a record in the table? #67

Closed
GCarneiroA opened this issue Dec 27, 2020 · 2 comments
Closed

Comments

@GCarneiroA
Copy link

GCarneiroA commented Dec 27, 2020

Dear, to return the field of auto increment of my table, currently I need to make a select with the data that were inserted to search for this information.

Somehow, it would be possible, when making an insertion, to return the line added in the database so that I can retrieve data such as auto increment fields and fields updated by internal triggers.

In my case, I need to return id AUTO_INCREMENT and created_time DATETIME

My actual code is:

int User::insertUser(const std::string &username, const std::string &password, const std::string &email)
{
    m_connection->insert(insert_into(m_userTable).set(
        m_userTable.username = username, m_userTable.password = password, m_userTable.email = email));
                
    const auto &row = m_connection->run(
        select(all_of(m_userTable)).from(m_userTable)
            .where(m_userTable.username == username and m_userTable.password == password and m_userTable.email == email)
    );
    return row.front().id;
}
@rbock
Copy link
Owner

rbock commented Dec 28, 2020

Hi,

insert_into returns the id. So I would use that one for the subsequent select.

Other than that, I don't know of a way that MySQL can yield inserted data as part of the insert call? PostgreSQL has the RETURNING clause. But I don't think there is an equivalent for MySQL?

Best,

Roland

@GCarneiroA
Copy link
Author

In MySQL I can use triggers to change data in tables during insert / update, for example, when inserting a new record the created_time field is filled with the current date and time.

insert_into returns the auto increment fields id ? I will test this, thanks :)

@rbock rbock closed this as completed Dec 18, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants