由於網上關於純C介面的文章並不多,本人在工作中剛好接觸到,在這裡做一點小分享。
廢話不說,先上下載地址 http://packages.couchbase.com…。
以下是官方程式碼:
#include <libcouchbase/couchbase.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
static void error_callback(lcb_t instance,
lcb_error_t err,
const char *errinfo)
{
fprintf(stderr, "Error %s: %s", lcb_strerror(instance, err),
errinfo ? errinfo : "");
exit(EXIT_FAILURE);
}
/* the callback invoked by the library when receiving a get response */
static void get_callback(lcb_t instance,
const void *cookie,
lcb_error_t error,
const lcb_get_resp_t *resp)
{
if (error != LCB_SUCCESS) {
fprintf(stderr, "Failed to retrieve "");
fwrite(resp->v.v0.key, 1, resp->v.v0.nkey, stderr);
fprintf(stderr, "": %s
", lcb_strerror(instance, error));
} else {
fprintf(stderr, "Data for key: "");
fwrite(resp->v.v0.key, 1, resp->v.v0.nkey, stderr);
fprintf(stderr, "" is : ");
fwrite(resp->v.v0.bytes, 1, resp->v.v0.nbytes, stderr);
}
(void)cookie; /* ignore */
}
int main(void)
{
struct lcb_create_st create_options;
lcb_t instance;
lcb_error_t err;
memset(&create_options, 0, sizeof(create_options));
create_options.v.v0.host = "myserver:8091";
create_options.v.v0.user = "mybucket";
create_options.v.v0.passwd = "secret";
create_options.v.v0.bucket = "mybucket";
err = lcb_create(&instance, &create_options);
if (err != LCB_SUCCESS) {
fprintf(stderr, "Failed to create libcouchbase instance: %s
",
lcb_strerror(NULL, err));
return 1;
}
/* set up the handler to catch all errors */
lcb_set_error_callback(instance, error_callback);
/* initiate the connect sequence in libcouchbase */
err = lcb_connect(instance);
if (err != LCB_SUCCESS) {
fprintf(stderr, "Failed to initiate connect: %s
",
lcb_strerror(NULL, err));
return 1;
}
/* run the event loop and wait until we`ve connected */
lcb_wait(instance);
/* set up a callback for our get requests */
lcb_set_get_callback(instance, get_callback);
{
lcb_get_cmd_t cmd;
const lcb_get_cmd_t *commands[1];
commands[0] = &cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.v.v0.key = "foo";
cmd.v.v0.nkey = 3;
err = lcb_get(instance, NULL, 1, commands);
if (err != LCB_SUCCESS) {
fprintf(stderr, "Failed to get: %s
",
lcb_strerror(NULL, err));
return 1;
}
}
lcb_wait(instance);
lcb_destroy(instance);
exit(EXIT_SUCCESS);
}
create_options.v.v0.host = “myserver:8091”;
**請注意以下兩句話,如果按照官方的標準呼叫的話,有可能提示管理員賬號無法訪問資料庫錯誤,註釋後成功訪問!!!**
//create_options.v.v0.user = "mybucket";
//create_options.v.v0.passwd = "secret";
create_options.v.v0.bucket = "mybucket";