我的数据库中有下表:
CREATE TABLE Alita.Cache (
ID INT NOT NULL AUTO_INCREMENT,
Created DATETIME NOT NULL,
Modified DATETIME NOT NULL,
ProcessState TINYINT NOT NULL,
Link VARCHAR(4000) CHARSET utf8,
Content VARCHAR(4000) CHARSET utf8,
CONSTRAINT PK_CACHE_ID PRIMARY KEY (ID));
要在此表中添加一行,我创建了以下存储过程:
DELIMITER //
DROP PROCEDURE IF EXISTS Alita.usp_AddCache //
CREATE PROCEDURE Alita.usp_AddCache (
IN _link VARCHAR(4000) CHARSET utf8,
IN _content VARCHAR(4000) CHARSET utf8,
OUT _linkId INT
)
PROC_START : BEGIN
START TRANSACTION;
SET @id := NULL;
SELECT @id := Id FROM Alita.Cache WHERE Link = _link;
SET _linkId := @id;
IF @id IS NULL THEN
INSERT INTO Alita.Cache VALUES(0, NOW(), NOW(), 0, _link, _content);
SELECT @id := Id FROM Alita.Cache WHERE Link = _link;
SET _linkId := @id;
LEAVE PROC_START;
END IF;
UPDATE Alita.Cache
SET Content = _content,
Modified = NOW(),
ProcessState = 0
WHERE Id = @id AND ProcessState = 2;
COMMIT;
END //
DELIMITER ;
现在我尝试从 MySql C++ 连接器调用这个存储过程。我将所有数据库交互代码封装在一个名为alita_db的类中。我使用了 MySQL 文档中的本教程。以下片段是连接的初始化:
alita::alita_db::alita_db(const alita::db_connection_info& db_connection_info)
{
if(db_connection_info._host.empty())
throw std::invalid_argument("Invalid Host.");
if(db_connection_info._username.empty())
throw std::invalid_argument("Invalid Username.");
if(db_connection_info._password.empty())
throw std::invalid_argument("Invalid Password.");
if(db_connection_info._scheme.empty())
throw std::invalid_argument("Invalid Scheme.");
this->_log = db_connection_info._log;
this->driver = get_driver_instance();
this->connection = this->driver->connect(
db_connection_info._host,
db_connection_info._username,
db_connection_info._password);
this->connection->setSchema(db_connection_info._scheme);
this->connection->setAutoCommit(false);
}
初始化后,我尝试执行调用usp_AddCache。以下是使用 MySql C++ 连接器 API 的调用片段。
std::unique_ptr<sql::Statement> stmt;
std::unique_ptr<sql::PreparedStatement> pstmt;
std::unique_ptr<sql::ResultSet> res;
stmt.reset(this->connection->createStatement());
pstmt.reset(this->connection->prepareStatement("CALL usp_AddCache(?, ?, @_linkId)"));
pstmt->setString(1, std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t>().to_bytes(link));
pstmt->setString(2, std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t>().to_bytes(content));
pstmt->execute();
代码成功执行,没有任何异常,并且自动递增 ID 计数器已更改。然而,当我使用 mysql CLI 查询数据时,我得到一个空集。我试图理解为什么插入实际上失败了。我的问题是如何解决这个问题。