MySQL NDB Cluster 8.1 手册
MySQL NDB Cluster 8.0 手册
NDB Cluster 内部手册
本示例演示从先前已创建并填充的表(参见 第 2.5.1.2 节,“NDB API 基本插入示例”)中删除一行。它在事务内使用单个 NdbOperation
执行删除操作,并使用 NdbError
处理错误。
您可以在之后通过运行读取示例(第 2.5.1.3 节,“NDB API 基本读取示例”)或在 mysql 客户端中执行 SELECT * FROM basic
来验证该行是否已删除。
本示例的源代码也可以在文件 storage/ndb/ndbapi-examples/ndbapi_basic/ndbapi_basic_delete.cpp
中找到。
#include <iostream>
#include <cstdlib>
#include <string>
#include <NdbApi.hpp>
class BasicDelete
{
public:
BasicDelete(const char * connectstring)
: m_connection(connectstring), m_ndb(&m_connection, "ndbapi_examples") {}
bool init();
bool do_delete(long long);
private:
Ndb_cluster_connection m_connection;
Ndb m_ndb;
inline bool on_error(const struct NdbError &error,
const std::string &explanation)
{
// prints error in format:
// ERROR <NdbErrorCode>: <NdbError message>
// explanation what went wrong on higher level (in the example code)
std::cout << "ERROR "<< error.code << ": " << error.message << std::endl;
std::cout << explanation << std::endl;
return false;
}
};
int main(int argc, char **argv)
{
if (argc != 3)
{
std::cout << "Usage: ndb_ndbapi_basic_delete <connectstring> <key: int>"
<< std::endl;
return EXIT_FAILURE;
}
const char *connectstring = argv[1];
const long long key = std::strtoll(argv[2], nullptr, 10);
ndb_init();
{
BasicDelete example(connectstring);
if (!example.init()) return EXIT_FAILURE;
// Let's verify delete
if (example.do_delete(key))
std::cout << "Done, check your database:\n"
<< "\t SELECT * FROM ndbapi_examples.basic;\n"
<< "\t or run the example: ndb_ndbapi_basic_read"
<< std::endl;
else return EXIT_FAILURE;
}
ndb_end(0);
return EXIT_SUCCESS;
}
bool BasicDelete::do_delete(long long key)
{
const NdbDictionary::Dictionary *dict = m_ndb.getDictionary();
const NdbDictionary::Table *table = dict->getTable("basic");
if (table == nullptr)
return on_error(dict->getNdbError(),
"Failed to access 'ndbapi_examples.basic'");
// The delete operation will be performed within single transaction
NdbTransaction *transaction = m_ndb.startTransaction(table);
if(transaction == nullptr)
return on_error(m_ndb.getNdbError(), "Failed to start transaction");
NdbOperation *operation = transaction->getNdbOperation(table);
if(operation == nullptr)
return on_error(transaction->getNdbError(),
"Failed to start delete operation");
operation->deleteTuple();
operation->equal("ATTR1", key);
if (transaction->execute(NdbTransaction::Commit) != 0)
return on_error(transaction->getNdbError(),
"Failed to execute transaction");
m_ndb.closeTransaction(transaction);
return true;
}
bool BasicDelete::init()
{
if (m_connection.connect() != 0)
{
std::cout << "Cannot connect to cluster management server" << std::endl;
return false;
}
if (m_connection.wait_until_ready(30, 0) != 0)
{
std::cout << "Cluster was not ready within 30 secs" << std::endl;
return false;
}
if (m_ndb.init() != 0)
return on_error(m_ndb.getNdbError(), "Failed to initialize ndb object");
return true;
}