0

我在表中添加了一条自动递增主键的记录。我没有运气检索这个新值。MySQL 文档说要SELECT LAST_INSERT_ID();在查询中使用。我已经这样做了,但无法检索结果。

根据结果​​集的元数据,数据类型是BIGINT,列名是LAST_INSERT_ID()。C++ 连接器有一个getUInt64()用于结果集的,我认为这是正确的使用方法。

ResultSet类声明包含以下内容:

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

该文档没有说明columnIndex是基于零还是基于一。我尝试了两种情况并获得sql::InvalidArgumentException了两种情况。

使用结果集元数据,我检索了列名并将其直接传递给getUInt64方法,但仍会收到sql::InvalidArgumentException. 这不是一个好的指示(当获取数据时返回的列名不起作用时)。

这是我的代码片段:

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);
}

这是调试输出(来自 wxLogDebug):

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

我的问题: 如何使用 MySQL C++ 连接器检索 LAST_INSERT_ID()?

我需要使用准备好的语句吗?

我在 Windows Vista 和 Windows XP 上使用 MySQL Connector C++ 1.0.5 和 Visual Studio 9 (2008)。

4

1 回答 1

0

解决。

我在检索数据之前插入了一个query_results->next()并且有效。

于 2010-05-11T18:58:50.740 回答