views:

62

answers:

1

I have added a record to my table which auto-increments the primary key. I am having no luck retrieving this new value. The MySQL documents say to use the SELECT LAST_INSERT_ID(); in a query. I have done this, but can't retrieve the results.

According the the metadata of the result set, the data type is BIGINT and the column name is LAST_INSERT_ID(). The C++ connector has a getUInt64() for the result set, which I assume is the correct method to use.

The ResultSet class declaration contains the following:

virtual uint64_t getUInt64(uint32_t columnIndex) const = 0;
virtual uint64_t getUInt64(const std::string& columnLabel) const = 0;

The documentation does not state whether the columnIndex is zero based or one based. I tried both and get sql::InvalidArgumentException for both cases.

Using the result set metadata, I retrieved the column name and passed it directly to the getUInt64 method and still receive the sql::InvalidArgumentException. This not a good indication (when the returned column name doesn't work when fetching the data).

Here is my code fragment:

std::string query_text;
query_text = "SELECT LAST_INSERT_ID();";
boost::shared_ptr<sql::Statement>   query(m_db_connection->createStatement());
boost::shared_ptr<sql::ResultSet>   query_results(query->executeQuery(query_text));
long    id_value = 0;
if (query_results)
{
    ResultSetMetaData p_metadata = NULL;
    p_metadata = query_results->getMetaData();
    unsigned int columns = 0;
    columns = p_metadata->getColumnCount();
    std::string column_label;
    std::string column_name;
    std::string column_type;
    for (i = 0; i < columns; ++i)
    {
        column_label = p_metadata->getColumnLabel(i);
        column_name  = p_metadata->getColumnName(i);
        column_type  = p_metadata->getColumnTypeName(i);
        wxLogDebug("Column label: \"%s\"\nColumn name: \"%s\"\nColumn type: \"%s\"\n",
                   column_label.c_str(),
                   column_name.c_str(),
                   column_type.c_str());
    }
    unsigned int    column_index = 0;
    column_index = query_results->findColumn(column_name);
    // The value of column_index is 1 (one).

    // All of the following will generate sql::InvalidArgumentException
    id_value = query_results->getUInt64(column_index);
    id_value = query_results->getUInt64(column_name);
    id_value = query_results->getUInt64(0);
    id_value = query_results->getUInt64(1);
    id_record.set_record_id(id_value);
}

Here is the debug output (from wxLogDebug):

10:50:58: Column label: "LAST_INSERT_ID()"
Column name: "LAST_INSERT_ID()"
Column type: "BIGINT"

My Question: How do I retrieve the LAST_INSERT_ID() using the MySQL C++ Connector?

Do I need to use a prepared statement instead?

I am using MySQL Connector C++ 1.0.5 on Windows Vista and Windows XP with Visual Studio 9 (2008).

A: 

Resolved.

I inserted a query_results->next() before retrieving the data and that worked.

Thomas Matthews